使用 purrr:map2 将行名称从一个嵌套列表传输到另一个嵌套列表

问题描述 投票:0回答:1

我似乎无法找到以下问题的解决方案: 我有两个嵌套列表(l1 和 l2),我想将 l2 中的信息作为 l1 中矩阵的行名称进行传输。为此,我需要使用嵌套的map2命令,但是我要么在l1中根本没有行名称(使用walk2或modify2而不是map2),要么整个矩阵被我想要作为行名称的测试替换。

这是我的想法:

library(tidyverse)

mat <- matrix(1:225, nrow = 15)
colnames(mat) <- LETTERS[1:15]
str(mat)
#>  int [1:15, 1:15] 1 2 3 4 5 6 7 8 9 10 ...
#>  - attr(*, "dimnames")=List of 2
#>   ..$ : NULL
#>   ..$ : chr [1:15] "A" "B" "C" "D" ...

rnames <- paste("This is name", 1:15)

l1 <- list(
  "sub1" = list(
    "a1" = mat,
    "a2" = mat,
    "a3" = mat
  ),
  "sub2" = list(
    "a1" = mat,
    "a2" = mat,
    "a3" = mat
  ))

l2 <- list(
  "sub1" = list(
    "a1" = rnames,
    "a2" = rnames,
    "a3" = rnames
  ),
  "sub2" = list(
    "a1" = rnames,
    "a2" = rnames,
    "a3" = rnames
  ))

l3 <- map2(.x = l1,
           .y = l2,
           .f = function(sol,csl) {
             map2(.x = sol,
                  .y = csl,
                  .f = function(so, cs) {
                    rownames(so) <- cs
                  }
             )
           }
)

l1[[1]][[1]] %>% view()
l2[[1]][[1]] %>% view()
l3[[1]][[1]] %>% view()

有人知道如何解决这个问题吗?

nested-loops purrr
1个回答
0
投票

您对

map2()
的调用未按预期工作,因为您没有显式地从内部函数返回任何内容,这导致该函数悄悄返回
rownames(so)
而不是
so

您可以通过将行

return(so)
添加到当前函数来解决此问题:

library(purrr)

l3 <- map2(.x = l1,
           .y = l2,
           .f = function(sol,csl) {
             map2(.x = sol,
                  .y = csl,
                  .f = function(so, cs) {
                    rownames(so) <- cs
                    ## Explicitly returning so will make this work:
                    return(so)    
                  }
             )
           }
)

创建于 2023-09-22,使用 reprex v2.0.2

可重现错误:

这里有一个小表示,显示了为什么事情没有按照您之前的预期进行:

implicit_return <- \(x) names(x) <- "Don't output this"

explicit_return <- \(x){
  names(x) <- "Don't output this"
  return(x)
}

unexpected_output <- implicit_return(1)
desired_output <- explicit_return(1)


## The implicit return of this function is the last assigned value, 
## which is the value we assigned to the rownames, rather than a renamed object
unexpected_output
#> [1] "Don't output this"

## Explicitly returning the object gives us the expected behaviour
desired_output
#> Don't output this 
#>                 1

创建于 2023-09-22,使用 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.