Search code examples
rpurrrrlang

Curly curly not recognizing quoted data


I'd like to feed two vectors into my custom function with purrr:map2. Unfortunately, when I do this, I get the error Error: Problem with `filter()` input `..2`. x Input `..2` must be of size 93 or 1, not size 9. ℹ Input `..2` is `!is.na(y)`.

How can I get my custom function to use arguments as data and run successfully with map2?

This is a MWE:

library(MASS)
data(Cars93)

crosstab_3way_custom <- function(y, z) {
pollster::crosstab_3way(Cars93, 
                x = Origin, 
                y= {{ y }}, 
                z = {{ z }},
                weight = rep(1, NROW(Cars93)),
                pct_type = "row")
}

combos <- expand.grid(c("Manufacturer", "Model", "Type"), c("Min.Price", "Price", "Max.Price"))
combos <- combos %>% map(as.character)

map2(combos[1], combos[2], function(y,z) crosstab_3way_custom(y,z))

Solution

  • To pass quoted variable use sym with !! :

    crosstab_3way_custom <- function(y, z) {
      pollster::crosstab_3way(data, 
                              x = Origin, 
                              y = !!sym(y),
                              z = !!sym(z),
                              weight = 1,
                              pct_type = "row")
    }
    
    purrr::map2(combos$Var1, combos$Var2, crosstab_3way_custom)