berehan
berehan

Reputation: 83

remove rows before specific values observed

I try to remove rows with value == "no" observed before at least one "yes" value in the column.

DT <- data.frame(id = c(1,1,1,2,2,2,2,2,3,3,3,3,3,3),
                value = c("no","yes","yes","no","no","yes","yes","yes","no","yes","yes","yes","no","no"))

Desired output:

 id value
   1   yes
   1   yes
   2   yes
   2   yes
   2   yes
   3   yes
   3   yes
   3   yes
   3    no
   3    no

Please help???

Upvotes: 0

Views: 51

Answers (1)

akrun
akrun

Reputation: 887028

We may do a group by filter

library(dplyr)
DT %>% 
   group_by(id) %>%
   filter(cumsum(value == 'yes') > 0) %>%
   ungroup

-output

# A tibble: 10 × 2
      id value
   <dbl> <chr>
 1     1 yes  
 2     1 yes  
 3     2 yes  
 4     2 yes  
 5     2 yes  
 6     3 yes  
 7     3 yes  
 8     3 yes  
 9     3 no   
10     3 no   

Upvotes: 1

Related Questions