Concatenate unique values from a column, but reset concatenation if any of the value already exists in the column using R programming

Viewed 70

Here is a df

id   name   
1    A  
1    B  
1    C   
1    A  
1    A  
2    C  
2    D  

desired output with calculated column

id   name calculated_column  
1    A    A,B,C  
1    B    A,B,C  
1    C    A,B,C  
1    A    A,B,C  
1    B    A,B,C  
1    C    A,B,C      
1    B    B,C    
1    C    B,C    
1    A    A  
1    A    A  
1    A    A  
2    C    C,D  
2    D    C,D  

I thought I could maybe create a sequence column and do a concatenation, but I'm really stuck.
I want to use dplyr, but I'm open to other suggestions.

df <- df %>% 
  group_by(id) %>% 
  arrange(date) %>% 
  mutate(calculated_column = ... ?)
1 Answers

A data.table solution:

library(data.table)

dt <- data.table(id = c(rep(1L, 11), rep(2L, 2)), nm = LETTERS[c(1,2,3,1,2,3,2,3,1,1,1,3,4)])
dt[, grp := nm <= shift(nm, fill = Inf), by = id][, grp := cumsum(grp)][, calc := .(.(nm)), by = grp][, c("nm", "calc")]
#>     nm  calc
#>  1:  A A,B,C
#>  2:  B A,B,C
#>  3:  C A,B,C
#>  4:  A A,B,C
#>  5:  B A,B,C
#>  6:  C A,B,C
#>  7:  B   B,C
#>  8:  C   B,C
#>  9:  A     A
#> 10:  A     A
#> 11:  A     A
#> 12:  C   C,D
#> 13:  D   C,D
Related