Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

dplyr - Identify elements from previous group in R

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.

question from:https://stackoverflow.com/questions/65952391/identify-elements-from-previous-group-in-r

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)])))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...