Question

I have two data elements in R:

      data1
1     M
2     T
3     Z
4     A
5     J

    data2 values
[1,] "A"   "aa"  
[2,] "J"   "ab"  
[3,] "M"   "ac"  
[4,] "T"   "ad"  
[5,] "Z"   "ae"  

I would like to get:

     data1 values
[1,] "M"   "ac" 
[2,] "T"   "ad" 
[3,] "Z"   "ae" 
[4,] "A"   "aa" 
[5,] "J"   "ab" 

How can I append the values to data 1 such that they are sorted according to the different order in data 1?

Was it helpful?

Solution

You can get this behavior with the match function:

dat1 = data.frame(data1=c("M", "T", "Z", "A", "J"), stringsAsFactors=FALSE)
dat2 = data.frame(data2=c("A", "J", "M", "T", "Z"),
                  values=c("aa", "ab", "ac", "ad", "ae"), stringsAsFactors=FALSE)
dat2[match(dat1$data1, dat2$data2),]
#   data2 values
# 3     M     ac
# 4     T     ad
# 5     Z     ae
# 1     A     aa
# 2     J     ab
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top