gpt4 book ai didi

r - 如何展平包含列表的 R 数据框?

转载 作者:行者123 更新时间:2023-12-03 21:23:38 27 4
gpt4 key购买 nike

我想找到最好的“R 方式”来展平如下所示的数据框:

  CAT    COUNT     TREAT
A 1,2,3 Treat-a, Treat-b
B 4,5 Treat-c,Treat-d,Treat-e

所以它的结构是这样的:
   CAT   COUNT1  COUNT2 COUNT3  TREAT1   TREAT2   TREAT3
A 1 2 3 Treat-a Treat-b NA
B 4 5 NA Treat-c Treat-d Treat-e

生成源数据帧的示例代码:
df<-data.frame(CAT=c("A","B"))
df$COUNT <-list(1:3,4:5)
df$TREAT <-list(paste("Treat-", letters[1:2],sep=""),paste("Treat-", letters[3:5],sep=""))

我相信我需要 rbind 和 unlist 的组合?任何帮助将不胜感激。
- 蒂姆

最佳答案

这是使用 base R 的解决方案,接受列表中任意长度的向量,无需指定要折叠的数据帧的哪些列。部分解决方案是使用 this 生成的回答。

df2 <- do.call(cbind,lapply(df,function(x){
#check if it is a list, otherwise just return as is
if(is.list(x)){
return(data.frame(t(sapply(x,'[',seq(max(sapply(x,length)))))))
} else{
return(x)
}
}))

从 R 3.2 开始,有 lengths替换 sapply(x, length)同样,
df3 <- do.call(cbind.data.frame, lapply(df, function(x) {
# check if it is a list, otherwise just return as is
if (is.list(x)) {
data.frame(t(sapply(x,'[', seq(max(lengths(x))))))
} else {
x
}
}))

使用的数据:
df <- structure(list(CAT = structure(1:2, .Label = c("A", "B"), class = "factor"), 
COUNT = list(1:3, 4:5), TREAT = list(c("Treat-a", "Treat-b"
), c("Treat-c", "Treat-d", "Treat-e"))), .Names = c("CAT",
"COUNT", "TREAT"), row.names = c(NA, -2L), class = "data.frame")

关于r - 如何展平包含列表的 R 数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34206003/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com