Remove rows below certain row number/condition by group

Viewed 418

I'm trying to subset a dataframe in R. It contains several categories. The first few rows for each category need to be removed. The number of rows to remove is inconsistent, but there is a row that indicates the cutoff. How do I remove everything above the cutoff (including that row) for each group?

Example data:

category <- c(rep("A", 3), rep("B", 5), rep("C", 4))
info <- as.character(c("Junk", "Border", "Useful", 
    "This", "is", "Useless", "Border", "Yes please", 
    "Unwanted", "Row", "Border", "Required"))
example_df <- data.frame(category, info)
example_df$row_number <- 1:nrow(example_df)

I can extract the row numbers of the border and the start of each group:

border_rows <- which(example_df$info == "Border")
start_rows <- example_df %>%
  group_by(category) %>%
  slice(1)
start_rows <- start_rows$row_number

I've tried the following, but this only removes the first two rows (i.e. the ones that need to be removed for group A).

for(i in 1:length(border_rows)) {
  new_df <- example_df[-(start_rows[i]:border_rows[i]), ]
}
1 Answers

You can easily do this with dplyr package -

library(dplyr)

example_df %>% 
  group_by(category) %>% 
  filter(row_number() > which(info == "Border")) %>% 
  ungroup()

# A tibble: 3 x 2
  category info      
  <fct>    <fct>     
1 A        Useful    
2 B        Yes please
3 C        Required
Related