Reputation: 31
Is there a way to sort and combine values from multiple columns into a single column using R?
For example: if I have a Data Frame as below:
[1] [2] [3]
[1] 2 bb cat
[2] 3 cc bat
[3] 5 xx sat
I want to write code that creates a new column that sort the first 3 values and then combines them into a comma separated value
Expected Output:
[1] [2] [3] [4]
[1] 2 bb cat 2,bb,cat
[2] 3 cc bat 3,bat,cc
[3] 5 xx sat 5,sat,xx
Upvotes: 0
Views: 65
Reputation: 1632
This is what you can do:
m<-(transpose(data.frame(apply(df, 1, sort)))) ## Sort the dataframe, transpose it back to normal
m<-data.frame(d=m$V1, a=m$V2, t=m$V3) #Rename the columns
cols <- c('d','a','t') #select the columns you want to paste together
m$x <- do.call(paste, c(m[cols], sep=",")) #create the new column with pasted columns
m
d a t x
1 2 bb cat 2,bb,cat
2 3 bat cc 3,bat,cc
3 5 sat xx 5,sat,xx
Upvotes: 1