#DATA
df <- data.frame(cols =
c(("Yellow + Blue + Green"),
("Blue + Yellow + Green"),
("Green + Yellow + Blue"),
("Green + Yellow + Red")), stringsAsFactors = FALSE)
#Split, sort, and then paste together
df$group = sapply(df$cols, function(a)
paste(sort(unlist(strsplit(a, " \\+ "))), collapse = ", "))
df
# cols group
#1 Yellow + Blue + Green Blue, Green, Yellow
#2 Blue + Yellow + Green Blue, Green, Yellow
#3 Green + Yellow + Blue Blue, Green, Yellow
#4 Green + Yellow + Red Green, Red, Yellow
#Or you can convert to factors too (and back to numeric, if you like)
df$group2 = as.numeric(as.factor(sapply(df$cols, function(a)
paste(sort(unlist(strsplit(a, " \\+ "))), collapse = ", "))))
df
# cols group group2
#1 Yellow + Blue + Green Blue, Green, Yellow 1
#2 Blue + Yellow + Green Blue, Green, Yellow 1
#3 Green + Yellow + Blue Blue, Green, Yellow 1
#4 Green + Yellow + Red Green, Red, Yellow 2
感謝d.b!奇妙的作品。我應該更具體的一件事是,我仍然希望它是a + b + c格式,但通過更改'collapse'語句可以輕鬆修復它。 – Ablum89