如何将数据框列的所有唯一值组合到字符串中

时间:2018-08-13 21:29:47

标签: r

我创建了一个看起来像这样的数据框

data <- data.frame(col1,col2,col3)
>data
    col1     col2    col3 
1   a1       b1      c1            
2   a1       b2      c2         
3   a1       b3      c3

,并希望转换成

    col1     col2         col3 
1   a1       b1,b2,b3     c1,c2,c3     

看来rbind是我想要的。但是在阅读了说明之后,我仍然不知道如何实现它。

2 个答案:

答案 0 :(得分:2)

创建示例数据集:

df <- data.frame(
    col1 = c("a1","a1","a1"),
    col2 = c("b1","b2","b3"),
    col3 = c("c1","c2","c3"),
    stringsAsFactors = FALSE
)

简短版本:

data.frame(lapply(df, function(x) paste(unique(x), collapse=",")))

说明和中间步骤:

#create a custom function to list unique elements as comma separated
myfun <- function(x) {
    paste(unique(x), collapse=",")
}

#apply our function to our dataframe's columns
temp <- lapply(df, myfun)

#temp is a list, turn it into a dataframe
result <- data.frame(temp)

答案 1 :(得分:0)

另一种选择是使用summarise_all

library(dplyr)

df %>% summarise_all(funs(paste(unique(.), collapse = ",")))
#   col1  col2     col3    
# 1 a1    b1,b2,b3 c1,c2,c3