Select rows in a dataframe in r based on values in

2019-01-26 11:53发布

问题:

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)

   a b
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 the rows where the a is either 2, 3, or 5 as specified by the idx.

I've tried the following; but none of them works.

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

This shouldn't be too hard.

回答1:

Use the %in% argument

df[df$a %in% idx,]