Вот один вариант с 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
data
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))