我们可以使用data.table
library(data.table)
DT <- setDT(df1)[,.(list(rep(names(df1)[-1], unlist(.SD)))) ,ID]
DT$V1
#[[1]]
#[1] "A" "A" "A" "A" "A" "B" "B" "B" "C" "C" "D"
#[[2]]
#[1] "A" "A" "A" "B" "B" "C" "C" "D"
#[[3]]
#[1] "A" "A" "A" "A" "B" "B" "C" "D" "E"
或者base R 选项是split
lst <- lapply(split(df1[-1], df1$ID), rep, x=names(df1)[-1])
lst
#$`1`
#[1] "A" "A" "A" "A" "A" "B" "B" "B" "C" "C" "D"
#$`2`
#[1] "A" "A" "A" "B" "B" "C" "C" "D"
#$`3`
#[1] "A" "A" "A" "A" "B" "B" "C" "D" "E"
如果我们想将“lst”写入 csv 文件,一种选择是将list 转换为data.frame,方法是在末尾附加NA 以使长度相等,同时转换为data.frame(如@ 987654330@ 是等长的list(列))
res <- do.call(rbind, lapply(lst, `length<-`, max(lengths(lst))))
或者使用stringi的方便函数
library(stringi)
res <- stri_list2matrix(lst, byrow=TRUE)
然后使用write.csv
write.csv(res, "yourdata.csv", quote=FALSE, row.names = FALSE)