如何将值与R中的公共列连接起来

时间:2018-05-09 08:59:25

标签: r

我试图通过旋转数据框来连接具有唯一列值的所有值

source

o / p

var = c("X","X","Y","Z","Z","Z")
value =c(1,4,7,21,3,45)
df = data.frame(var,value)

提前致谢

3 个答案:

答案 0 :(得分:1)

使用dplyr

df %>%
  mutate(value = paste0("(",value,")")) %>%
  group_by(var) %>%
  summarise_at(vars(value), paste, collapse = ",")

答案 1 :(得分:0)

我们可以将aggregatec

一起使用
aggregate(value ~ var, data = df, c)

  var     value
1   X      1, 4
2   Y         7
3   Z 21, 3, 45

答案 2 :(得分:0)

您可以拆分数据集,并使用值系列执行您想要的任务:

var = c("X","X","Y","Z","Z","Z")
value =c(1,4,7,21,3,45)
df = data.frame(var,value)

dflist <- split(df, df$var)

sapply(dflist, function(x) paste(x$value, collapse = ","))

结果:

    X         Y         Z 
"1,4"       "7" "21,3,45"