简体   繁体   English

如何在列表中组合列表向量的成员

[英]How to combine member of list vector within a list

I have the following list of list: 我有以下列表清单:

nfoo <- list(a = list(x = 1:3, y = 11:13), b = list(x = 1:3, y = 100:102))

It looks like this: 它看起来像这样:

 > nfoo
$a
$a$x
[1] 1 2 3

$a$y
[1] 11 12 13


$b
$b$x
[1] 1 2 3

$b$y
[1] 100 101 102

What I want to do is to combine the list within the list, resulting: 我想要做的是组合列表中的列表,结果:

$a
[1] 1 2 3 11 12 13

$b
[1] 1 2 3 100 101 102

How can I achieve that? 我怎样才能做到这一点?

We can use lapply with unlist 我们可以使用lapplyunlist

lapply(nfoo, unlist, use.names = FALSE)

#$a
#[1]  1  2  3 11 12 13

#$b
#[1]  1   2   3 100 101 102

Using purrr , we can do that by using map and flatten.* 使用purrr ,我们可以通过使用mapflatten.*

library(purrr)
map(nfoo, flatten_int)

If we know that each of the sublists of foo contain vectors x and y (which is true for the example in the question) then: 如果我们知道foo每个子列表都包含向量xy (对于问题中的示例,则为true),则:

lapply(foo, with, c(x, y))

giving: 赠送:

$a
[1]  1  2  3 11 12 13

$b
[1]   1   2   3 100 101 102

Use lapply with docall and the concatenate function (which also works with lists): 使用lapplydocall和concatenate函数(也适用于列表):

output <- lapply(nfoo, function(x) do.call(c, x))
output

$a
x1 x2 x3 y1 y2 y3 
 1  2  3 11 12 13 

$b
 x1  x2  x3  y1  y2  y3 
  1   2   3 100 101 102 

使用lapply遍历列表,然后unlist列表以将每个列表转换为向量:

lapply(nfoo, unlist)
library(tidyverse)
nfoo%>%map(unlist)

# $a
# x1 x2 x3 y1 y2 y3 
#  1  2  3 11 12 13 
# 
# $b
#  x1  x2  x3  y1  y2  y3 
#   1   2   3 100 101 102 

For the sake of completeness, there is another variant which uses Reduce() within lapply() 为了完整起见,还有另一种变体,它在lapply()使用Reduce() lapply()

lapply(nfoo, Reduce, f = c)
 $a [1] 1 2 3 11 12 13 $b [1] 1 2 3 100 101 102 

Using do.call . 使用do.call

Map(do.call, nfoo, w="c")
# $a
# x1 x2 x3 y1 y2 y3 
#  1  2  3 11 12 13 
# 
# $b
# x1  x2  x3  y1  y2  y3 
#  1   2   3 100 101 102 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM