如何将一个包含多行数据框的列表转换为向量列表

4

我有一个包含5个tibble的列表,每个tibble只包含一行:

<list_of<
  tbl_df<
    one  : integer
    two  : integer
    three: integer
    four : integer
  >
>[5]>
[[1]]
# A tibble: 1 x 4
    one   two three  four
  <int> <int> <int> <int>
1     1     3     2     4

[[2]]
# A tibble: 1 x 4
    one   two three  four
  <int> <int> <int> <int>
1     2     0     1     5

[[3]]
# A tibble: 1 x 4
    one   two three  four
  <int> <int> <int> <int>
1     3     2     1     4

[[4]]
# A tibble: 1 x 4
    one   two three  four
  <int> <int> <int> <int>
1     4     9    11    19

[[5]]
# A tibble: 1 x 4
    one   two three  four
  <int> <int> <int> <int>
1     4     3     2     1

list <- structure(list(structure(list(one = 1L, two = 3L, three = 2L, 
    four = 4L), row.names = c(NA, -1L), class = c("tbl_df", "tbl", 
"data.frame")), structure(list(one = 2L, two = 0L, three = 1L, 
    four = 5L), row.names = c(NA, -1L), class = c("tbl_df", "tbl", 
"data.frame")), structure(list(one = 3L, two = 2L, three = 1L, 
    four = 4L), row.names = c(NA, -1L), class = c("tbl_df", "tbl", 
"data.frame")), structure(list(one = 4L, two = 9L, three = 11L, 
    four = 19L), row.names = c(NA, -1L), class = c("tbl_df", 
"tbl", "data.frame")), structure(list(one = 4L, two = 3L, three = 2L, 
    four = 1L), row.names = c(NA, -1L), class = c("tbl_df", "tbl", 
"data.frame"))), ptype = structure(list(one = integer(0), two = integer(0), 
    three = integer(0), four = integer(0)), class = c("tbl_df", 
"tbl", "data.frame"), row.names = integer(0)), class = c("vctrs_list_of", 
"vctrs_vctr", "list"))

我期望得到的输出应该是一个包含5个向量的列表,就像这样:

[[1]]
[1]     1     3     2     4

[[2]]
[1]     2     0     1     5

[[3]]
[1]     3     2     1     4

[[4]]
[1]     4     9    11    19

[[5]]
[1]     4     3     2     1

我现在已经尝试相当长的时间来解决这个问题(一开始觉得这只是一个简单的问题)。但是我无法解决它。

2个回答

3
你可以使用 unlist 函数来取消列表的嵌套。
lapply(list, unlist, use.names = FALSE)

#[[1]]
#[1] 1 3 2 4

#[[2]]
#[1] 2 0 1 5

#[[3]]
#[1] 3 2 1 4

#[[4]]
#[1]  4  9 11 19

#[[5]]
#[1] 4 3 2 1

2
使用 purrr
library(purrr)
map(list, flatten_int)

-输出

[[1]]
[1] 1 3 2 4

[[2]]
[1] 2 0 1 5

[[3]]
[1] 3 2 1 4

[[4]]
[1]  4  9 11 19

[[5]]
[1] 4 3 2 1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接