将矢量压缩为逗号分隔的字符串

时间:2017-07-27 15:03:08

标签: r dplyr

如何将unique的结果压缩为逗号分隔的字符串?

temp3 <- data.frame(categoryId=c(1,1,1,2),ballot1=c("yes","yes","no","200"))
temp3 %>% group_by(categoryId)
      %>% mutate(responses=unique(ballot1))

预期输出:

1 yes,no
1 yes,no
1 yes,no
2 200

1 个答案:

答案 0 :(得分:1)

我们可以按'categoryId'进行分组,获取'ballot1'中的unique元素和paste这些元素

library(dplyr) 
temp3 %>% 
   group_by(categoryId) %>%
   mutate(ballot1 = toString(unique(ballot1)))
# A tibble: 4 x 2
# Groups:   categoryId [2]
#   categoryId ballot1
#       <dbl>   <chr>
#1          1 yes, no
#2          1 yes, no
#3          1 yes, no
#4          2     200