我有一个嵌套的数据列表。它的长度是132,每一项是一个长度为20的列表。是否有一种快速的方法可以将这种结构转换为具有132行和20列数据的数据帧?
下面是一些示例数据:
l <- replicate(
132,
as.list(sample(letters, 20)),
simplify = FALSE
)
我有一个嵌套的数据列表。它的长度是132,每一项是一个长度为20的列表。是否有一种快速的方法可以将这种结构转换为具有132行和20列数据的数据帧?
下面是一些示例数据:
l <- replicate(
132,
as.list(sample(letters, 20)),
simplify = FALSE
)
当前回答
从不同的角度;
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.
其他回答
如果您的列表具有相同尺寸的元素,则可以使用来自tidyverse的bind_rows函数。
# Load the tidyverse
Library(tidyverse)
# make a list with elements having same dimensions
My_list <- list(a = c(1, 4, 5), b = c(9, 3, 8))
## Bind the rows
My_list %>% bind_rows()
结果是一个有两行的数据帧。
修正样本数据,使其符合原始描述“每个项目是一个长度为20的列表”
mylistlist <- replicate(
132,
as.list(sample(letters, 20)),
simplify = FALSE
)
我们可以像这样把它转换成一个数据帧:
data.frame(t(sapply(mylistlist,c)))
Sapply将其转换为矩阵。 data.frame将矩阵转换为数据帧。
导致:
假设你的列表是L,
data.frame(Reduce(rbind, L))
用rbind
do.call(rbind.data.frame, your_list)
编辑:以前的版本返回list的data.frame而不是向量(正如@IanSudbery在评论中指出的那样)。
对于使用purrr系列解决方案的并行(多核,多会话等)解决方案,使用:
library (furrr)
plan(multisession) # see below to see which other plan() is the more efficient
myTibble <- future_map_dfc(l, ~.x)
其中l是列表。
要对最有效的计划()进行基准测试,您可以使用:
library(tictoc)
plan(sequential) # reference time
# plan(multisession) # benchamark plan() goes here. See ?plan().
tic()
myTibble <- future_map_dfc(l, ~.x)
toc()