nickobob456
nickobob456

Reputation: 1

How to concatenate in R other values of same group into a column based off unique identifier

Letter Group      
    A  1    
    B  1  
    C  1    
    D  2  
    E  2  

to become:

Letter Group  SameGroup  
A      1      B,C  
B      1      A,C  
C      1      A,B  
D      2      E  
E      2      D

Upvotes: 0

Views: 38

Answers (2)

akrun
akrun

Reputation: 886948

Here is an option using data.table. We convert the 'data.frame' to 'data.table' (setDT(df)), grouped by 'Group', loop through the sequence of rows, subset the 'Letter' based on the sequence, convert to list and assign (:=) as 'SameGroup'

library(data.table)
setDT(df)[, SameGroup := list(lapply(seq_len(.N), function(i) Letter[-i])), Group]
df
#   Letter Group SameGroup
#1:      A     1       B,C
#2:      B     1       A,C
#3:      C     1       A,B
#4:      D     2         E
#5:      E     2         D

Upvotes: 0

nicola
nicola

Reputation: 24480

You can try:

df$SameGroup<-mapply(function(x,y)
                       toString(setdiff(x,y)),
                     ave(df$Letter,df$Group,FUN= list),df$Letter)  
#  Letter Group SameGroup
#1      A     1      B, C
#2      B     1      A, C
#3      C     1      A, B
#4      D     2         E
#5      E     2         D

Data

df<-structure(list(Letter = c("A", "B", "C", "D", "E"), Group = c(1, 
1, 1, 2, 2)), .Names = c("Letter", "Group"), row.names = c(NA, 
-5L), class = "data.frame")

Upvotes: 3

Related Questions