在地图循环中使用作为字符串的函数名称?

Dou*_*Fir 7 r purrr

一些代码:

mymtcars <- mtcars %>% head %>% rownames_to_column('model') %>% group_by(vs) %>% nest
mymtcars
     vs data             
  <dbl> <list>           
1     0 <tibble [3 × 11]>
2     1 <tibble [3 × 11]>
Run Code Online (Sandbox Code Playgroud)

我可以在这个列表列 df 上拟合线性模型,如下所示:

mymtcars %>% 
+   mutate(mod = map(.x = data, ~ lm(.x$mpg ~ .x$cyl)))
# A tibble: 2 x 3
# Groups:   vs [2]
     vs data              mod   
  <dbl> <list>            <list>
1     0 <tibble [3 × 11]> <lm>  
2     1 <tibble [3 × 11]> <lm>  
Run Code Online (Sandbox Code Playgroud)

如果我的函数名称是一个字段怎么办?

mymtcars2 <- mtcars %>% head %>% rownames_to_column('model') %>% group_by(vs) %>% nest %>% crossing(func = c('lm'))
> mymtcars2
# A tibble: 2 x 3
     vs data              func 
  <dbl> <list>            <chr>
1     0 <tibble [3 × 11]> lm   
2     1 <tibble [3 × 11]> lm
Run Code Online (Sandbox Code Playgroud)

我试了一下:

mymtcars2 %>% 
+   mutate(mod = map2(.x = data, .y = func, ~ .y(.x$mpg ~ .x$cyl)))
Error: Problem with `mutate()` input `mod`.
x could not find function ".y"
? Input `mod` is `map2(.x = data, .y = func, ~.y(.x$mpg ~ .x$cyl))`.
Run Code Online (Sandbox Code Playgroud)

如何传递函数以在 map 中调用,然后在上面的块中调用它?

PKu*_*mar 6

可能match.fun在 map2 内部使用,如下所示:

   models <-  mymtcars2 %>% 
       mutate(mod = map2(.x = data, .y = func, ~ match.fun(.y)(.x$mpg ~ .x$cyl)))
Run Code Online (Sandbox Code Playgroud)

输出

[[1]]

Call:
match.fun(.y)(formula = .x$mpg ~ .x$cyl)

Coefficients:
(Intercept)       .x$cyl  
  36.926733    -2.728218  


[[2]]

Call:
match.fun(.y)(formula = .x$mpg ~ .x$cyl)

Coefficients:
(Intercept)       .x$cyl  
    41.9400      -3.8025  
Run Code Online (Sandbox Code Playgroud)