[英]combine elements of list of lists with the same name
I have a list of 4 lists with the same name: 我列出了4个同名的列表:
lst1 <-
list(list(c(1,2,3)),list(c(7,8,9)),list(c(4,5,6)),list(c(10,11,12)))
names(lst1) <- c("a","b","a","b")
I want to combine the sub lists together (first "a" with second "a", first "b" with second "b": 我想将子列表组合在一起(第一个“a”和第二个“a”,第一个“b”和第二个“b”:
result <- list(list(c(1,2,3,4,5,6)),list(c(7,8,9,10,11,12)))
names(result) <- c("a","b")
I have tried multiple things, but can't figure it out. 我尝试了很多东西,但无法弄清楚。
Since lst1["a"]
isn't going to give us all the elements of lst1
named a
, we are going to need to work with names(lst1)
. 由于
lst1["a"]
不会给我们命名为a
的lst1
所有元素, lst1
我们需要使用names(lst1)
。 One base R approach would be 一种基本的R方法是
nm <- names(lst1)
result <- lapply(unique(nm), function(n) unname(unlist(lst1[nm %in% n])))
names(result) <- unique(nm)
result
# $a
# [1] 1 2 3 4 5 6
#
# $b
# [1] 7 8 9 10 11 12
Another option is to use unlist
first and then split
the resulting vector. 另一个选择是首先使用
unlist
,然后split
生成的向量。
vec <- unlist(lst1)
split(unname(vec), sub("\\d+$", "", names(vec)))
#$a
#[1] 1 2 3 4 5 6
#$b
#[1] 7 8 9 10 11 12
只需将具有相同名称的元素分组并将其unlist
:
tapply(lst1,names(lst1),FUN=function(x) unname(unlist(x)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.