Home > Back-end >  How subselect all rows who's index number "greater than" some value in R?
How subselect all rows who's index number "greater than" some value in R?

Time:12-24

Say I have a dataframe as follows:

A<-c(1,2,3,4)
B<-c(5,6,7,8)
C<-c(9,10,11,12)
data<-data.frame(A,B,C)

I know that I can subselect just rows 2 and 3 by the following:

data[2:3,]

My question is: how can I achieve the same by effectively saying "all rows with an index number greater than 1"? (I.e., the row indices for "data" are 1, 2, and 3. So, by requesting row indices ">1", I should get rows 2 and 3 only.)

CodePudding user response:

You can use nrow to get the total rows and then use greater than operator.

data[1:nrow(data) > 1, ]

Also, for example if you need all indices greater than 2:

data[-c(1:2), ]

CodePudding user response:

tidyverse option. This is a bit verbose compared to using base R. To keep the row index, you have to change the row name to a column, filter, then change the column with the row name back to the actual row name. filter does not preserve row names.

library(tidyverse)

data %>%
  rownames_to_column() %>%
  filter(rowname > 1) %>%
  column_to_rownames()
  • Related