将两个具有相同元素名称的列表组合成元素名称为R

时间:2018-11-14 10:45:01

标签: r

我有两个列表,一个带有矩阵,一个带有向量。两者都具有相等的命名元素。看起来像这样:

set.seed(1)
mat_list <- list("2009" = matrix(runif(n = 9, min = 0, max = 10), 3, 3),
                 "2010" = matrix(runif(n = 9, min = 0, max = 10), 3, 3))
vec_list <- list("2009" = c(runif(n = 3, min = 0, max = 10)),
                 "2010" = c(runif(n = 3, min = 0, max = 10)))

我要创建一个包含元素20092010的新列表,其中包含各自的矩阵和向量,以便我可以在lapply调用中对它们进行访问。我实际的日期还有些长,所以我很高兴不必明确引用这些年。

我发现了很多类似的问题,但是我不知道如何将答案应用于我的情况。谢谢!

1 个答案:

答案 0 :(得分:2)

使用purrr包和map2函数,您可以执行以下操作:

#install_packages("purrr")
set.seed(1)
mat_list <- list("2009" = matrix(runif(n = 9, min = 0, max = 10), 3, 3),
                 "2010" = matrix(runif(n = 9, min = 0, max = 10), 3, 3))
vec_list <- list("2009" = c(runif(n = 3, min = 0, max = 10)),
                 "2010" = c(runif(n = 3, min = 0, max = 10)))

l <- purrr::map2(mat_list, vec_list, function(x,y) list(x,y))
#l <- purrr::map2(mat_list, vec_list, ~list(.x,.y)) #shorter notation
#l <- purrr::map2(mat_list, vec_list, list) #even shorter

#x and y inside the map2 are the elements of each list at each iteration, 
#so we can combine them in a list

感谢@markus:

l <- Map(list, mat_list, vec_list) # no need for another package