Tidyr::crossing 超过 2 个参数 (..1,..2,..3)

Tidyr::crossing more than 2 parameters (..1,..2,..3)

library(dplyr)
library(fpp2) # for prison dataset
library(hts) # forecasting function

# prepare group time series
prison.gts <- gts(prison/1e3, characters = c(3,1,9),
                  gnames = c("State", "Gender", "Legal",
                             "State*Gender", "State*Legal",
                             "Gender*Legal"))


result_obj <- tidyr::crossing(methods = c('bu', 'comb'), 
                              fmethods = c('arima'),
                              algorithms = c("lu", "cg", "chol", "recursive", "slm")) %>%
  mutate(forecast_result = purrr::map2(methods, fmethods, algorithms,
                                              ~forecast.gts(prison.gts,
                                                            method = ..1, 
                                                            fmethod = ..2, 
                                                            algorithms = ..3)))

我正在使用 tidyr::crossing 创建可能的参数组合,然后这些参数组合将成为 forecast.gts() 的输入。

因为我有超过 2 个参数,所以使用 ..x 符号映射参数,即 ..1、..2、..3 https://purrr.tidyverse.org/reference/map2.html

但是,似乎每个组合的结果都是 NULL。

如果我单独调用函数,它会给出结果。

forecast.gts(prison.gts, method="bu", fmethod="arima", algorithms = 'lu')

map2 只需要 2 个参数。对于超过 2 个参数,使用 pmap :

library(dplyr)
library(fpp2) 
library(hts)

result_obj <- tidyr::crossing(
                methods = c('bu', 'comb'), 
                fmethods = c('arima'),
                algorithms = c("lu", "cg", "chol", "recursive", "slm")) %>%
   mutate(forecast_result = purrr::pmap(list(methods, fmethods, algorithms),
                                   ~forecast.gts(prison.gts,
                                                 method = ..1, 
                                                 fmethod = ..2, 
                                                 algorithms = ..3)))

但是,此 returns 一条错误消息表明

Error: The recursive algorithm does not support a gts object.

所以您可能需要将其从 algorithms 向量中删除,之后它就可以正常工作了。