Choosing rows in a data frame in r based on values โ€‹โ€‹in one row

I have a toy data frame.

a = rep(1:5, each=3) b = rep(c("a","b","c"), each = 5) df = data.frame(a,b) ab 1 1 a 2 1 a 3 1 a 4 2 a 5 2 a 6 2 b 7 3 b 8 3 b 9 3 b 10 4 b 11 4 c 12 4 c 13 5 c 14 5 c 15 5 c 

I also have an index.

 idx = c(2,3,5) 

I want to select all rows where a is either 2, 3, or 5, as indicated by idx.

I tried the following: but none of them work.

 df[df$a==idx, ] subset(df, df$a==idx) 

It should not be too complicated.

+6
source share
1 answer

Use the argument %in%

 df[df$a %in% idx,] 
+13
source

All Articles