Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select multiple rows conditioning on ID in R

Tags:

r

subset

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?

like image 322
Fred Avatar asked Dec 06 '11 05:12

Fred


People also ask

How do I select multiple rows of data in R?

Multiple row selections are possible by pressing Ctrl or Shift while selecting the rows. Holding Ctrl while selecting the row adds it to the current selection, and holding Shift extends selection to the selected row.

How do I select a range of rows in R?

By using bracket notation on R DataFrame (data.name) we can select rows by column value, by index, by name, by condition e.t.c. You can also use the R base function subset() to get the same results. Besides these, R also provides another function dplyr::filter() to get the rows from the DataFrame.

How do I select a row by index in R?

Use the square bracket operator with df[] notation to select rows by index in R, The syntax of this notation is df[rows, columns], replace rows with the index number, index range, or list of index values.


1 Answers

You want %in%, not ==.

out <- test[test$ID %in% c(201, 202), ]
out <- subset(test, ID %in% c(201, 202))
like image 187
Hong Ooi Avatar answered Oct 05 '22 18:10

Hong Ooi