我有一个嵌套的数据列表。它的长度是132,每一项是一个长度为20的列表。是否有一种快速的方法可以将这种结构转换为具有132行和20列数据的数据帧?

下面是一些示例数据:

l <- replicate(
  132,
  as.list(sample(letters, 20)),
  simplify = FALSE
)

当前回答

或者你可以使用tibble包(来自tidyverse):

#create examplelist
l <- replicate(
  132,
  as.list(sample(letters, 20)),
  simplify = FALSE
)

#package tidyverse
library(tidyverse)

#make a dataframe (or use as_tibble)
df <- as_data_frame(l,.name_repair = "unique")



其他回答

修正样本数据,使其符合原始描述“每个项目是一个长度为20的列表”

mylistlist <- replicate(
  132,
  as.list(sample(letters, 20)),
  simplify = FALSE
)

我们可以像这样把它转换成一个数据帧:

data.frame(t(sapply(mylistlist,c)))

Sapply将其转换为矩阵。 data.frame将矩阵转换为数据帧。

导致:

从不同的角度;

install.packages("smotefamily")
library(smotefamily)
library(dplyr)

data_example = sample_generator(5000,ratio = 0.80)
genData = BLSMOTE(data_example[,-3],data_example[,3])
#There are many lists in genData. If we want to convert one of them to dataframe.

sentetic=as.data.frame.array(genData$syn_data)
# as.data.frame.array seems to be working.

或者你可以使用tibble包(来自tidyverse):

#create examplelist
l <- replicate(
  132,
  as.list(sample(letters, 20)),
  simplify = FALSE
)

#package tidyverse
library(tidyverse)

#make a dataframe (or use as_tibble)
df <- as_data_frame(l,.name_repair = "unique")



我也想提出这个解决方案。尽管它看起来与其他解决方案相似,但它使用了rbind。从胶合板包装填充。这在列表缺少列或NA值的情况下非常有利。

l <- replicate(10,as.list(sample(letters,10)),simplify = FALSE)

res<-data.frame()
for (i in 1:length(l))
  res<-plyr::rbind.fill(res,data.frame(t(unlist(l[i]))))

res

用rbind

do.call(rbind.data.frame, your_list)

编辑:以前的版本返回list的data.frame而不是向量(正如@IanSudbery在评论中指出的那样)。