从列表列表中创建数据框,但每个元素都是一列

Make dataframe from list of lists but each element a column

我想从列表列表创建一个数据框,其中生成的数据框每个元素都有一列,行是单独的。这很难解释,所以我会尝试制作一个示例来继续工作。

假设我的列表如下:

myList <- list(
  list(L=c(1,2,3),a=c(1,2,3),b=c(1,2,3)),
  list(L=c(4,5,6),a=c(4,5,6),b=c(4,5,6)),
  list(L=c(7,8,9),a=c(7,8,9),b=c(7,8,9)))

生成的数据框如下所示:

df <- data.frame(ind = c(1,2,3),
  L.1 = c(1,4,7),L.2 = c(2,5,8), L.3 = c(3,6,9),
  a.1 = c(1,4,7),a.2 = c(2,5,8), a.3 = c(3,6,9),
  b.1 = c(1,4,7),b.2 = c(2,5,8), b.3 = c(3,6,9))

我试过使用

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

df <- bind_rows(myList, .id="column_label")

但是每个人产生三行而不是所需的输出。

我也试过使用: df <- bind_cols(myList) 但这会将列划分为每个列表。

知道怎么做吗?

谢谢, 夏娃

如果名字总是一一匹配,你可以简单地做,

do.call(rbind, lapply(myList, unlist))
#     L1 L2 L3 a1 a2 a3 b1 b2 b3
#[1,]  1  2  3  1  2  3  1  2  3
#[2,]  4  5  6  4  5  6  4  5  6
#[3,]  7  8  9  7  8  9  7  8  9
librayr(purrr) # load the purrr library
library(magrittr) # load the magrittr library
myList %>% 
    map(unlist) %>% # for each element of myList, apply the unlist function which makes it a vector of 9 floats.
    map(as.list) %>% # transform this vector into a list
    map_dfr(data.frame) # and then transofrm this list into a data.frame row.

一个purrr选项可以是:

myList %>%
 map_df(~ bind_rows(unlist(.)))

  L1 L2 L3 a1 a2 a3 b1 b2 b3
1  1  2  3  1  2  3  1  2  3
2  4  5  6  4  5  6  4  5  6
3  7  8  9  7  8  9  7  8  9

还包括 ind 列,加上 dplyr:

myList %>%
 map_df(~ bind_rows(unlist(.))) %>%
 mutate(ind = 1:n())

您也可以在使用 sapply() 后转置为 unlist():

as.data.frame(t(sapply(myList, unlist)))
  L1 L2 L3 a1 a2 a3 b1 b2 b3
1  1  2  3  1  2  3  1  2  3
2  4  5  6  4  5  6  4  5  6
3  7  8  9  7  8  9  7  8  9