我在下面有一个数据框,其中包含colomn" id"中的常见元素。
df<- data.frame(id=c("x1","x2","x3","x4","x5","x2"),figure=sample(1:5,6,replace=T))
id figure
x1 5
x2 5
x3 3
x4 2
x5 5
x2 2
我想将行与相同的元素组合在一起作为数据框中的列表,所以它看起来像这样
id figure
x1 5
x2 c(2,5)
x3 3
x4 2
x5 5
答案 0 :(得分:1)
您需要的功能是拆分:
split(df$figure,df$id)
答案 1 :(得分:1)
如果你只是需要一个很好的概述使用:
require(data.table)
setDT(df)[,.(figure= paste(figure, collapse = " ")), by=id]
这给了你:
id figure
1: x1 4
2: x2 2 2
3: x3 5
4: x4 5
5: x5 1
答案 2 :(得分:1)
dplyr
方式。
df1 <- data.frame(id=c("x1","x2","x3","x4","x5","x2"),figure=sample(1:5,6,replace=T))
df1 %>% group_by(id) %>%
mutate(figure = as.character(figure),
figure = ifelse(length(figure)>=2,
paste(figure, collapse=" "), figure) ) %>%
unique