我有两个列表,一个带有矩阵,一个带有向量。两者都具有相等的命名元素。看起来像这样:
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)))
我要创建一个包含元素2009
和2010
的新列表,其中包含各自的矩阵和向量,以便我可以在lapply
调用中对它们进行访问。我实际的日期还有些长,所以我很高兴不必明确引用这些年。
我发现了很多类似的问题,但是我不知道如何将答案应用于我的情况。谢谢!
答案 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