从列表列表中获取数据帧,但每个元素为一列

问题描述 投票:4回答:4

我想从列表列表中创建一个数据框,其中结果数据框每个元素都有一列,而行是单独的。很难解释,所以我将尝试产生一个示例进行处理。

可以说我的名单如下:

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)但这会将列划分为每个列表。

任何想法如何解决?

谢谢,前夕

r list dataframe nested-lists
4个回答
5
投票

如果名称始终是一对一匹配,则只需这样做,

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

2
投票

一个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())

2
投票

您也可以在使用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

0
投票
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.

0
投票

您可以使用purrr::flatten_dfc()

purrr::flatten_dfc(myList)

# A tibble: 3 x 9
      L     a     b    L1    a1    b1    L2    a2    b2
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1     1     1     1     4     4     4     7     7     7
2     2     2     2     5     5     5     8     8     8
3     3     3     3     6     6     6     9     9     9
© www.soinside.com 2019 - 2024. All rights reserved.