将函数列表应用于值向量

我有一个命名向量列表,其中每个向量名称对应一个我想应用于向量每个元素的函数。我可以使用以下代码完成此操作:

funs <- list(mean = c("mpg", "wt"), 
             var = c("qsec", "am"))

lapply(seq_along(funs), function(i){
  fun <- get(names(funs)[i])
  vars <- funs[[i]]
  
  res <- lapply(vars, function(x){
    fun(mtcars[[x]])
  })

})

有没有更好的方法来做同样的事情?理想的解决方案是,按重要性排序,速度更快、内存效率更高且更紧凑。提前致谢。

回答

使用 {purrr} 你可以这样做:

funs <- list(mean = c("mpg", "wt"), 
             var = c("qsec", "am"))
library(purrr)

imap(funs, ~ map(mtcars[.x], match.fun(.y)))
#> $mean
#> $mean$mpg
#> [1] 20.09062
#> 
#> $mean$wt
#> [1] 3.21725
#> 
#> 
#> $var
#> $var$qsec
#> [1] 3.193166
#> 
#> $var$am
#> [1] 0.2489919

由reprex 包(v0.3.0)于 2021 年 5 月 11 日创建

或与基数 R 相同的结果:

Map(function(x,nm) lapply(mtcars[x], nm), funs, names(funs))

  • You should not use `get` unless you explicitly define the mode ie `get(.y, mode = 'function')` Otherwise it will throw an error if there is an object in the global environment with the name corresponding to any of the functions given. You should rather consider `match.fun(.y)`

以上是将函数列表应用于值向量的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>