【问题标题】:Combine two list with equal element names into list of lists by element name R按元素名称 R 将两个具有相同元素名称的列表组合成列表列表
【发布时间】:2018-11-14 10:45:00
【问题描述】:

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

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 调用中访问它们。我的实际数据还有几年,所以我很高兴不必明确引用这些年份。

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

【问题讨论】:

    标签: r


    【解决方案1】:

    使用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
    

    【讨论】:

    • 你实际上可以做 purrr::map2(mat_list, vec_list, list) 或者没有额外的包 Map(list, mat_list, vec_list)
    • 不知道Map。我使用了较长的版本,因为当人们不习惯*apply/map 看到它时,我会发现它更清晰。
    猜你喜欢
    • 2020-07-08
    • 1970-01-01
    • 1970-01-01
    • 2013-09-03
    • 2014-06-23
    • 1970-01-01
    • 2021-11-29
    • 2013-09-17
    相关资源
    最近更新 更多