如果我有如下数据,我想获取每个组ID的ID信息。希望任何人都能帮助我。谢谢
ID GroupID Income age
1 1 5000 45
2 1 5000 27
3 2 3000 21
4 2 3000 35
5 2 3000 17
6 2 3000 16
我想要这样的数据:
groupID"1" ID"1" ID"2" income"5000"
groupID"2" ID"3" ID"4" ID"5" ID"5" income"3000"
最好的问候
答案 0 :(得分:0)
这里是data.table
和splitstackshape
的一个选项
library(data.table)
library(splitstackshape)
out <- setDT(df1)[, .(ID = toString(paste("ID", ID)),
Income = toString(paste("income", unique(Income)))),
.(GroupID = paste('groupID', GroupID))]
cSplit(out, "ID", ", ")
# GroupID Income ID_1 ID_2 ID_3 ID_4
#1: groupID 1 income 5000 ID 1 ID 2 <NA> <NA>
#2: groupID 2 income 3000 ID 3 ID 4 ID 5 ID 6
df1 <- structure(list(ID = 1:6, GroupID = c(1L, 1L, 2L, 2L, 2L, 2L),
Income = c(5000L, 5000L, 3000L, 3000L, 3000L, 3000L), age = c(45L,
27L, 21L, 35L, 17L, 16L)), class = "data.frame", row.names = c(NA,
-6L))