从r中的第二个数据帧过滤r行名称中的数据帧

时间:2012-07-24 12:18:42

标签: r filter dataframe

我有data.frame:

df1<-data.frame("Sp1"=1:6,"Sp2"=7:12,"Sp3"=13:18)
rownames(df1)=c("A","B","C","D","E","F")

df1

  Sp1 Sp2 Sp3
A   1   7  13
B   2   8  14
C   3   9  15
D   4  10  16
E   5  11  17
F   6  12  18

我按df1的截止值过滤rowSums(df1)并返回我想要包含在下游分析中的网站(行名称)。

include<-rownames(df1[rowSums(df1)>=22,])
include

[1] "B" "C" "D" "E" "F"

我有第二个data.frame:

df2<-data.frame(site.x=c("A","B","C"), site.y=c("D","E","F"),score=1:3)

  site.x site.y score
1      A      D     1
2      B      E     2
3      C      F     3

我想过滤df2,使其仅包含df2$site.xdf2$site.y与“include”中列出的网站完全相同的行,即过滤掉包含“A”并返回的行。 / p>

  site.x site.y score    
2      B      E     2
3      C      F     3

我试过了:

filter<-df2$site.x == include & df2$site.y == include   

filtered<-df2[filter,]

感谢您的任何建议!

ANSWER

在%

中使用%
filter<-df2$site.x %in% include & df2$site.y =%in% include  

filtered<-df2[filter,]
filtered

   site.x site.y score
 2      B      E     2
 3      C      F     3

1 个答案:

答案 0 :(得分:1)

对我而言,它适用于:

filter<-df2$site.x %in% include & df2$site.y %in% include
df2[filter,]

事实上,你在问题的最后两行放了df1而不是df2