0

I have a data.frame and a vector. I want to output only the rows from the data frame that have values in a column in common with the vector v.

For example:

v = (1,2,3,4,5)

df =

     A    B
1    a    2
2    b    6 
3    c    4 
4    d    1
5    e    8

What I want to do is, if df$b has any values of v in it then output the row. Basically if df$b[i] isn't in v then remove the row for i= 1:nrows(df)

output should be

     A    B
1    a    2
2    c    4 
3    d    1

since 2,4 and 1 are in v.

thelatemail
  • 91,185
  • 12
  • 128
  • 188
Hike
  • 9
  • 2

1 Answers1

3

You should make use of the %in% operator.

v <- c(1, 2, 3, 4, 5)
df <- read.table(text =
"     A    B
1    a    2
2    b    6
3    c    4
4    d    1
5    e    8", header = TRUE)

out <- df[df$B %in% v, ]

This gives:

  A B
1 a 2
3 c 4
4 d 1
maccruiskeen
  • 2,748
  • 2
  • 13
  • 23