我有一个具有相同名称的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")
我想将子列表组合在一起(第一个“ 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")
我已经尝试了多种方法,但无法弄清楚。
答案 0 :(得分:4)
由于lst1["a"]
不会为我们提供名为lst1
的{{1}}的所有元素,因此我们需要使用a
。一种基本的R方法是
names(lst1)
答案 1 :(得分:3)
另一种选择是先使用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
答案 2 :(得分:2)
只需对具有相同名称的元素进行分组并unlist
:
tapply(lst1,names(lst1),FUN=function(x) unname(unlist(x)))