首页 > 解决方案 > Tidyr::crossing 2 个以上的参数 (..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')

标签: rtidyversepurrrfurrr

解决方案


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

但是,这会返回一条错误消息

错误:递归算法不支持 gts 对象。

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


推荐阅读