2013-03-13 44 views
3

我親愛的我有一個問題,我有兩個dataframes這樣的:匹配兩段dataframes考慮兩個變量具有相同的水平

z=data.frame(x1=c(1,2,5,4,9,1,4,2,9,21),x2=c(2,2,2,4,8,9,1,9,1,1),x3=c("a","b","b","a","a","b","b","b","a","a")) 
z1=data.frame(y=c("a","b"),x=c("protein","cell")) 

我一直在努力,以配合Z,使用Z1考慮到在Z1 Y的水平與z的x3中的級別相同,並且我希望在所有數據幀z中顯示一個顯示z1的變量z的新列。我想這樣的一些;我用比賽,但我沒有得到那個結果。

x1 x2 x3 N 
1 1 2 a protein 
2 2 2 b cell 
3 5 2 b cell 
4 4 4 a protein 
5 9 8 a protein 
6 1 9 b cell 
7 4 1 b cell 
8 2 9 b cell 
9 9 1 a protein 
10 21 1 a protein 
+1

如果其中一個答案解決您的問題,請接受它。 – 2013-03-23 03:33:33

回答

3

您正在尋找merge

您可以設置by.yby.x適當的,因爲它們不具有相同的名稱在兩列

merge(z,z1,by.y='y', by.x = 'x3') 
    x3 x1 x2  x 
1 a 1 2 protein 
2 a 21 1 protein 
3 a 4 4 protein 
4 a 9 8 protein 
5 a 9 1 protein 
6 b 5 2 cell 
7 b 2 2 cell 
8 b 4 1 cell 
9 b 2 9 cell 
10 b 1 9 cell 

要使用match

z$x <- z1[match(z$x3,z1$y),'x'] 
z 
    x1 x2 x3  x 
1 1 2 a protein 
2 2 2 b cell 
3 5 2 b cell 
4 4 4 a protein 
5 9 8 a protein 
6 1 9 b cell 
7 4 1 b cell 
8 2 9 b cell 
9 9 1 a protein 
10 21 1 a protein 
+0

謝謝我尋找那個(/' - '/) – Duck 2013-03-13 22:46:01

0

這種方法使用包qdap

library(qdap) 
z$N <- z$x3 %l% z1 

產量:

> z 
    x1 x2 x3  N 
1 1 2 a protein 
2 2 2 b cell 
3 5 2 b cell 
4 4 4 a protein 
5 9 8 a protein 
6 1 9 b cell 
7 4 1 b cell 
8 2 9 b cell 
9 9 1 a protein 
10 21 1 a protein 
相關問題