从列表中提取函数

Extracting a function from a list

我无法从函数列表中提取函数。并且必须使用 [[1]] 运算符。见下文:

library(tibble)
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

fns = tibble(fn_name = c('plus', 'multiply'),
             fn = list(function(x,y) x + y,
                       function(x,y) x * y))


my_x = 2
my_y = 3
my_fn_name = 'plus'

my_fn = fns %>% 
  filter(fn_name == my_fn_name) %>% 
  pull(fn)

my_fn[[1]](my_x, my_y)
#> [1] 5

reprex package (v0.3.0)

于 2020-12-09 创建

是否有更优雅的方式来做到这一点,而无需调用 my_fn[[1]]?我不认为函数可以是向量,这就是为什么我不能像将 pull 应用于原子向量时那样对待它。

也许是这个?

fns %>% 
  filter(fn_name == my_fn_name) %>% 
  unlist() %>%
  purrr::pluck("fn")

#> function(x,y) x + y
#> <environment: 0x000001cfdcd6d4f8>

加上purrr,你可以做:

fns %>%
 filter(fn_name == my_fn_name) %>% 
 pull("fn") %>%
 map_dbl(exec, !!!list(my_x, my_y))

[1] 5

我们也可以

library(dplyr)
library(purrr)
fns %>%
     filter(fn_name == my_fn_name) %>% 
     transmute(out = pluck(fn, 1)(my_x, my_y)) %>%
     pull(out)
#[1] 5