组合具有相同名称的列表列表的元素 [英] combine elements of list of lists with the same name

查看:24
本文介绍了组合具有相同名称的列表列表的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有相同名称的4个列表的列表:

I have a list of 4 lists with the same name:

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":

I want to combine the sub lists together (first "a" with second "a", first "b" with second "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.

推荐答案

由于 lst1 ["a"] 不会为我们提供 lst1 的所有元素名为 a ,我们将需要使用 names(lst1).一种基本的R方法是

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). One base R approach would be

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

这篇关于组合具有相同名称的列表列表的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆