使用purrr:walk2时找不到对象.x

时间:2019-06-21 13:02:29

标签: r purrr

我正在尝试在purrr::walk2处抛出一个函数,即:

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

我不知道为什么{x1在函数dl_stats19()中没有被选中

1 个答案:

答案 0 :(得分:1)

有两种可能的解决方案。第一种,也是最简单的方法,是在函数名称之前包含波浪号,如下所示:

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

您还可以使用匿名函数并按位置匹配参数,例如:

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))