Select multiple rows conditioning on ID in R

Fred picture Fred · Dec 6, 2011 · Viewed 37.2k times · Source

I tried to select the rows based on their ID. For example, in a data frame called test, ID 201 has 6 rows of data, ID 202 has 6 rows of data too, and 203, 204..... etc.

Now I only want to extract 201 and 202 from the dataset, so it should have 12 rows altogether. However

out <- test[test$ID==c(201,202), ]
out <- subset(test, ID==c(201,202))

only returns three 201 and three 202, which are Row 1, Row 3, Row of 5 8 10 12.

Can anyone provide some suggestions that how I can do this in R?

Answer

Hong Ooi picture Hong Ooi · Dec 6, 2011

You want %in%, not ==.

out <- test[test$ID %in% c(201, 202), ]
out <- subset(test, ID %in% c(201, 202))