Ryan Knight
Ryan Knight

Reputation: 1368

use invoke_map to pass variable names as args

I would like to use invoke_map to call a list of functions. I have a set of variable names that I would like to use as arguments to each of the functions. Ultimately the variable names will used with group_by.

Here's an example:

library(dplyr)
library(purrr)
first_fun <- function(...){
  by_group = quos(...)
  mtcars %>%
    group_by(!!!by_group) %>%
    count()
}

second_fun <- function(...){
  by_group = quos(...)
  mtcars %>%
    group_by(!!!by_group) %>%
    summarise(avg_wt = mean(wt))
}

first_fun(mpg, cyl) # works
second_fun(mpg, cyl) # works

both_funs <- list(first_fun, second_fun)

both_funs %>%
  invoke_map(mpg, cyl) # What do I do here?

I have tried various attempts to put the variable names in quotes, enquo them, use vars, reference .data$mpg, etc, but I am stabbing in the dark a bit.

Upvotes: 4

Views: 677

Answers (1)

moodymudskipper
moodymudskipper

Reputation: 47340

The issue is not that you're using dots, it's that you're using names and when map2_impl is called these arguments are evaluated.

Try this and explore the environment:

debugonce(map2)
both_funs %>% invoke_map("mpg", "cyl")

This works on the other hand:

first_fun2 <- function(...){
  mtcars %>%
  {do.call(group_by_,list(.,unlist(list(...))))} %>%
    count()
}

second_fun2 <- function(...){
  mtcars %>%
  {do.call(group_by_,list(.,unlist(list(...))))} %>%
    summarise(avg_wt = mean(wt))
}

both_funs2 <- list(first_fun2, second_fun2)
both_funs2 %>% invoke_map("mpg", "cyl") 

# [[1]]
# # A tibble: 25 x 2
# # Groups:   mpg [25]
# mpg     n
# <dbl> <int>
#   1  10.4     2
# 2  13.3     1
# 3  14.3     1
# 4  14.7     1
# 5  15.0     1
# 6  15.2     2
# 7  15.5     1
# 8  15.8     1
# 9  16.4     1
# 10  17.3     1
# # ... with 15 more rows
# 
# [[2]]
# # A tibble: 25 x 2
# mpg avg_wt
# <dbl>  <dbl>
#   1  10.4 5.3370
# 2  13.3 3.8400
# 3  14.3 3.5700
# 4  14.7 5.3450
# 5  15.0 3.5700
# 6  15.2 3.6075
# 7  15.5 3.5200
# 8  15.8 3.1700
# 9  16.4 4.0700
# 10  17.3 3.7300
# # ... with 15 more rows

Upvotes: 2

Related Questions