R语言 当`map()`嵌套在`mutate()`内部时,拼接不起作用

fdx2calv  于 2023-05-11  发布在  其他
关注(0)|答案(1)|浏览(95)

我尝试获取一列索引向量,并将它们拼接到pluck()调用中,以获取这些索引处的值。如果我在顶层的map()调用中这样做,它可以正常工作,但当在mutate()内部调用map()时,它无法识别.x参数。有人能解释一下为什么吗?有没有什么语法我漏掉了?

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(purrr)

lst <-
    list(a=1, b=list(c=2, d=3))
str(lst)
#> List of 2
#>  $ a: num 1
#>  $ b:List of 2
#>   ..$ c: num 2
#>   ..$ d: num 3

#;; Note what is at index c(2L, 2L)
lst[[c(2L, 2L)]]
#> [1] 3

#;; Put that index in a dataframe column.
idx_df <-
    tibble(idx=list(c(2L, 2L)))
idx_df
#> # A tibble: 1 × 1
#>   idx      
#>   <list>   
#> 1 <int [2]>

#;; This does not work, but I expect it to, as I believe it should work
#;; analagously to what is below.
tryCatch({
    idx_df |>
        mutate(val = map_dbl(idx, ~ pluck(lst, !!!.x)))
}
, error=\(e) e)
#> <simpleError in quos(..., .ignore_empty = "all"): object '.x' not found>

#;; This works, but I should be able to do this in a mutate call.
idx_df$val <-
    map_dbl(idx_df$idx, ~ pluck(lst, !!!.x))
idx_df
#> # A tibble: 1 × 2
#>   idx         val
#>   <list>    <dbl>
#> 1 <int [2]>     3

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

oprakyz7

oprakyz71#

如突出显示的,问题似乎是在计算!!!时出现的。作为一个简单的解决方法,您可以创建一个临时函数,以便在调用该函数之前不会计算!!!

library(dplyr)
library(purrr)

lst <-
  list(a=1, b=list(c=2, d=3))

idx_df <-
  tibble(idx=list(c(2L, 2L)))

pluck_loc <-  function(x) {
  pluck(lst, !!!x)
}

idx_df |>
  mutate(val = map_dbl(idx, pluck_loc))
#> # A tibble: 1 × 2
#>   idx         val
#>   <list>    <dbl>
#> 1 <int [2]>     3

相关问题