Object .x not found when using purrr:walk2

Viewed 727

I'm trying to throw a function at purrr::walk2 ie:

library(stats19)
library(purrr)

walk2(.x = 2017, .y = "Accidents", .f = dl_stats19(year = .x, type = .y, data_dir = "./data", file_name = paste0("stats19_", .x, "_", .y), ask = FALSE))

# Error in dl_stats19(year = .x$years, type = types, data_dir = data_dir, : object '.x' not found

I can't figure out why .x isn't being picked up in the function dl_stats19()

1 Answers

There are a couple of possible solutions. The first, and simplest, is to include a tilde before the function name, like so:

walk2(.x = 2017, 
      .y = "Accidents", 
      .f = ~ dl_stats19(year = .x, 
                        type = .y, 
                        data_dir = "./data", 
                        file_name = paste0("stats19_", .x, "_", .y), 
                        ask = FALSE))

You could also use an anonymous function and match arguments by position, like this:

walk2(.x = 2017, 
      .y = "Accidents", 
      .f = function(a, b) dl_stats19(year = a, 
                                     type = b, 
                                     data_dir = "./data", 
                                     file_name = paste0("stats19_", a, "_", b), 
                                     ask = FALSE))
Related