anthe.sevenants

How to NEGATIVELY subset by index in R

2023-05-09

In R, you can subset a data frame or matrix by supplying a vector of the indices of the rows you want to keep:

odd_rows <- awesome_matrix[c(1, 3, 5),]

This feature of R is well documented.

However, what if you wanted to use that vector of indices to tell R what rows NOT to keep? You want to invert the selection procedure. To do this, simply add a minus symbol (-) in front of the vector with indices:

even_rows <- awesome_matrix[-c(1, 3, 5),]

This also works with variables:

uneven_indices <- c(1, 3, 5)
even_rows <- awesome_matrix[-uneven_indices,]