0

下面我试图给出我的问题的最小可重复示例。在我最初的问题中,我尝试使用 furrr 包在多个数据集上并行运行代码。为了说明这一点,以下是示例数据:

df1 <- tibble(
  x = c(1:5), 
  y = c(1:5), 
  Date = as.Date(c("2015-08-08", "2015-08-15", "2015-08-22", 
                        "2015-08-29","2015-09-05"))
)

df2 <- tibble(
  x = c(2:6), 
  y = c(2:6), 
  Date = as.Date(c("2015-08-08", "2015-08-15", "2015-08-22", 
                   "2015-08-29","2015-09-05"))
)


list_df <- list(df1, df2)

以下是示例函数:

calc_ex <- function(y){
  
  sum(y[,1] + y[,2])
}

roll_calc_ex <- function(y){
  
  y <- y %>%
    dplyr::mutate(output = runner::runner(x = .,
                                                k = "14 days",
                                                idx = Date,
                                                na_pad = TRUE,
                                                f = calc_ex))
}

roll_calc_ex2 <- function(y){
  
  
  estimate <- runner::runner(x = y,
                             k = "14 days",
                             idx = y$Date,
                             na_pad = TRUE,
                             f = calc_ex)
  
  y <- y %>% 
    dplyr::mutate(output = estimate)
 
  return(y)
}

如果我运行以下两行代码中的任何一个

purrr::map(list_df, roll_calc_ex)
purrr::map(list_df, roll_calc_ex2)

然后我得到了我想要的,即

[[1]]
# A tibble: 5 x 4
      x     y Date       output
  <int> <int> <date>      <int>
1     1     1 2015-08-08     NA
2     2     2 2015-08-15     NA
3     3     3 2015-08-22     10
4     4     4 2015-08-29     14
5     5     5 2015-09-05     18

[[2]]
# A tibble: 5 x 4
      x     y Date       output
  <int> <int> <date>      <int>
1     2     2 2015-08-08     NA
2     3     3 2015-08-15     NA
3     4     4 2015-08-22     14
4     5     5 2015-08-29     18
5     6     6 2015-09-05     22

但是,如果我尝试运行以下两行代码,则会收到以下相应的错误消息:

furrr::future_map(list_df, roll_calc_ex)

Error: Problem with `mutate()` column `output`.
i `output = runner::runner(...)`.
x comparison (1) is possible only for atomic and list types


furrr::future_map(list_df, roll_calc_ex2)

Error in x[[1]] == as.name("runner") : 
  comparison (1) is possible only for atomic and list types

不幸的是,我无法将任何错误追踪到我了解出了什么问题以及如何修复它的地步。解决问题的任何帮助将不胜感激。

我还应该提到,我已经能够使用 rowr::rollApply() 而不是 runner::runner() 来解决问题。但是,对于我更复杂的问题,我需要 runner,因为然后可以选择在哪些日期应用函数 calc_ex(),以及让估计窗口依赖于日期而不是依赖于观察的数量。同样,我们将不胜感激对解决问题的任何帮助。提前感谢任何花时间阅读这篇文章的人。

更新:我也尝试直接使用期货来 purrr::map(),它返回了相同的错误信息

plan(multisession, workers = 4)

values(purrr::map(list_df, ~future(roll_calc_ex(.x))))

Error: Problem with `mutate()` column `output`.
i `output = runner::runner(...)`.
x comparison (1) is possible only for atomic and list types
4

0 回答 0