使用dplyr在函数内的分组数据中应用向量

时间:2017-07-24 15:29:20

标签: r dplyr forecasting

尝试在r中使用带有grouped_by的预测。如果我捐赠使用该函数,并指定要使用的向量不是问题,但如果我在函数中设置向量,则返回NA:s。

有什么建议吗?

fun <- function(data, VECTOR) {
  a <- data %>% 
    group_by(company_id) %>% 
    mutate(count = n()) %>% 
    filter(count > 2) %>%
    arrange(company_id, date) %>%
    do(data.frame(forecast = forecast::forecast(.$VECTOR, h = 2)))
  return(a)
}

fun(data = test, VECTOR = oms)

数据:

 company_id STMT_TO_DT NET_SALES
      <chr>     <date>     <dbl>
1  55600727 2011-12-01   1951000
2  55600727 2012-12-01   1934000
3  55600727 2013-12-01   1902000
4  55600727 2014-12-01   1951000
5  55600727 2015-12-01   1930000
6  55600784 2012-06-01       413
7  55600784 2013-06-01       476
8  55600784 2014-06-01       301
9  55600784 2015-06-01       385
10 55600784 2016-06-01      1867

如前所述,如果没有使用任何功能:

a <- data %>% 
group_by(company_id) %>% 
mutate(count = n()) %>% 
filter(count > 2) %>%
arrange(company_id, STMT_TO_DT) %>%
do(data.frame(forecast = forecast::forecast(.$NET_SALES, h = 2)))`

获得以下结果:

company_id forecast.Point.Forecast forecast.Lo.80 forecast.Hi.80 forecast.Lo.95 forecast.Hi.95
      <chr>                   <dbl>          <dbl>          <dbl>          <dbl>          <dbl>
1 55600727                 1936302   1.906994e+06    1965610.447       1891478.7440    1981125.371
2 55600727                 1936302   1.905888e+06    1966715.952   1889788.0197    1982816.095
3 55600784                     791   9.511396e+01       1486.886      -273.2659       1855.266
4 55600784                     854   1.581140e+02       1549.886      -210.2659       1918.266`

0 个答案:

没有答案