Detect a specific pattern between rows

Viewed 67

I have the following data:

tibble(id = c(1000, 2000, 2000, NA, 2000, NA, 1000, 2000))

The data come ordered like this and I would like to add an indicator yes/no if an id is preceded by the same id and has a row with NA in between. (I don't care about other ids in between as long as there is at least one NA between the two ids.)

How can I achieve this (preferably using dplyr)?

The solution should look like this:

     id outcome
  <dbl> <chr>  
1  1000 no     
2  2000 no     
3  2000 no     
4    NA no     
5  2000 yes    
6    NA no     
7  1000 yes    
8  2000 yes      
1 Answers

yes when id is duplicated (second or more occurrence of a same value), not NA (complete.cases) and after the first NA (cumany(is.na(id))).

library(dplyr)
tbl %>% 
  mutate(outcome = ifelse(cumany(is.na(id)) & duplicated(id) & complete.cases(id), "yes", "no"))

# A tibble: 8 x 2
     id outcome
  <dbl> <chr>  
1  1000 no     
2  2000 no     
3  2000 no     
4    NA no     
5  2000 yes    
6    NA no     
7  1000 yes    
8  2000 yes
Related