Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select rows in a dataframe 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)

   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.

like image 594
wen Avatar asked Feb 24 '14 08:02

wen


1 Answers

Use the %in% argument

df[df$a %in% idx,] 
like image 128
JeremyS Avatar answered Nov 01 '22 01:11

JeremyS