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?
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.
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.
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.
You want %in%
, not ==
.
out <- test[test$ID %in% c(201, 202), ]
out <- subset(test, ID %in% c(201, 202))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With