Identify elements from previous group in R

Viewed 57

I have a dataframe that looks like this and I try to generate the last column Searched

 tibble::tribble(   ~Group, ~Element, ~Searched,
      "A",    "aaa",        NA,
      "A",    "bbb",        NA,
      "A",    "ccc",        NA,
      "B",    "aaa",      TRUE,
      "B",    "bbb",      TRUE,
      "B",    "ddd",     FALSE,
      "C",    "aaa",      TRUE,
      "C",    "bbb",      TRUE,
      "C",    "ccc",     FALSE   )

I suppose I can find something with a combination of group_by and lead/lag but not sure how.

1 Answers

Here's a way in tidyverse :

library(tidyverse)

df %>%
  group_by(Group) %>%
  summarise(Element = list(Element)) %>%
  mutate(last_element = lag(Element), 
         result = map2(Element, last_element, `%in%`)) %>%
  unnest(c(result, Element)) %>%
  select(-last_element)

# Group Element result
#  <chr> <chr>   <lgl> 
#1 A     aaa     FALSE 
#2 A     bbb     FALSE 
#3 A     ccc     FALSE 
#4 B     aaa     TRUE  
#5 B     bbb     TRUE  
#6 B     ddd     FALSE 
#7 C     aaa     TRUE  
#8 C     bbb     TRUE  
#9 C     ccc     FALSE 

and with similar logic in base R :

tmp<- split(df$Element, df$Group)
df$result <- c(mapply(`%in%`, tmp, c(NA, tmp[-length(tmp)])))
Related