2014-05-16 69 views
0

我有R中兩個數據元素:與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" 

我想獲得:

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

我怎麼能值追加到數據1,使得它們按數據1中的不同順序排序?

回答

2

你可以得到的match功能此行爲:

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