r - 将嵌套列表转换为数据框

标签 r list dataframe rbind do.call

I have a list of items, each of them has two items, one is a list and the other one is a character expression We generate de lists

My_list <- list()
My_list$'product1' <- list()
My_list$'product1'$'sales' <- c(1,2,3)
My_list$'product1'$'model' <- "arima"
My_list$'product2'$'sales' <- c(4,5,6)
My_list$'product2'$'model' <- "prophet"

This is the desired output shape

df1 <- data.frame(product=c("product1"),sales1 = 1, sales2 = 2, sales3 = 3)
df2 <- data.frame(product=c("product2"),sales1 = 4, sales2 = 5, sales3 = 6)
solution <- rbind (df1,df2)

I have tried something like this

solution <- lapply(My_list, function(x) do.call(rbind, lapply(x, as.data.frame)))
solution <- do.call(rbind, Map(cbind, product = names(My_list), My_list))
```7

最佳答案

这是一个基于 R 的简单版本,

as.data.frame(matrix(unlist(My_list), nrow = length(My_list), byrow = TRUE))
#  V1 V2 V3      V4
#1  1  2  3   arima
#2  4  5  6 prophet

您可以轻松地进行修改以适应您的预期输出(更改名称并将 V4 转换为 product1product2),即

#save the data frame
d1 <- as.data.frame(matrix(unlist(My_list), nrow = length(My_list), byrow = TRUE))
#Set the column names
d1 <- setNames(d1, c(paste0('sales', seq(ncol(d1) - 1)), 'Product'))
#Change the variable under `Product`
d1$Product <- paste0('Product', seq(nrow(d1)))

d1
#  sales1 sales2 sales3  Product
#1      1      2      3 Product1
#2      4      5      6 Product2

关于r - 将嵌套列表转换为数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60615943/

相关文章:

在 R 数据框中保留数值精度?

r - 如何在 R6 对象中调度 summary() 方法

python - 添加要设置的列表

python - 在 Python 中基于地类网格求和土地面积网格

python - Pandas 数据框作为 matplotlib.pyplot.boxplot 的输入

r - 将包含分隔字符串的数据框列拆分为多个列,并保留拆分字符串的特定部分

mysql - 无法连接到R中的本地MySQL服务器

python - 斐波那契函数列表

python - 如何用行中的前一个可用值填充 nan 值?

python - 对 Pandas 数据帧进行计数、平均和连接