Mathica
Mathica

Reputation: 1303

how to select rows of a dataframe whose value are the same as another dataframe in a certain column in R

let say my df1 and df2 are as below:
df1:

      [,1] [,2] [,3]
 [1,] "n"  "11" "13"
 [2,] "a"  "18" "14"
 [3,] "b"  "13" "10"

df2:

     [,1] [,2] [,3]
[1,] "n"  "11" "13"
[2,] "a"  "ll" "kk"
[3,] "b"  "jj" "ii"

I want a dubset of df2, such that it contains only those rows of df2 who has same values as df1 in column 1.

     [,1] [,2] [,3]
[1,] "a"  "ll" "kk"
[2,] "b"  "jj" "ii"

I thought

df.2.sub <- df2[df2$CertainColumn == df1$Specific.column]

can work. but it does not. would you help me with this please?

Upvotes: 0

Views: 2723

Answers (2)

akrun
akrun

Reputation: 887881

It seems to be a matrix. Thus, the $ wouldn't work. We can use [ for extracting the first column

df2[df2[,1] %in% df1[,1],]

Upvotes: 1

d3hero23
d3hero23

Reputation: 392

close but need to use the "%in%" operator

df.2.sub <- df2[df2$CertainColumn %in% df1$Specific.column,]

Upvotes: 2

Related Questions