1

I have the 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

I filter df1 by a cutoff value for rowSums(df1) and return sites (row names) that I want to include in downstream analysis.

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

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

I have a second 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

I want to filter df2 such that it only includes rows where df2$site.x and df2$site.y are exactly equal to the sites listed in 'include' i.e. filtering out the row containing "A" and returning.

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

I have tried :

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

filtered<-df2[filter,]

Thanks for any advice!

ANSWER

use %in%

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
2
  • maybe with %in% instead of ==
    – Pop
    Jul 24, 2012 at 12:27
  • no dice! Do you think it has something to do with how 'include' is structured?
    – Elizabeth
    Jul 24, 2012 at 12:30

1 Answer 1

1

For me, it works with :

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

In fact, you've put df1 instead of df2 in the last two lines of your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.