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
转换为 product1 和 product2),即
#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/