My dataset looks like following. I am trying to predict the 'amount' for next 2 months using either the ets, auto.arima, Prophet or any other model. But my issue is that I would like to predict amount based on each groups ie A,B,C for next 2 months. I am not sure how to do that in R ?
data = data.frame(Date=c('2017-01-01', '2017-02-01', '2017-03-01', '2017-04-01','2017-05-01','2017-06-01','2017-01-01', '2017-02-01', '2017-03-01', '2017-04-01','2017-05-01','2017-06-01','2017-01-01', '2017-02-01', '2017-03-01', '2017-04-01','2017-05-01','2017-06-01'),
Group=c('A','A','A','A','A','A','B','B','B','B','B','B','C','C','C','C','C','C'),
Amount=c('12.1','13','15','10','12','9.0','12.5','13.3','14.8','11','10','12.1','13','12.2','11','10.9','13.4','11.1'))
data
Date Group Amount
1 2017-01-01 A 12.1
2 2017-02-01 A 13
3 2017-03-01 A 15
4 2017-04-01 A 10
5 2017-05-01 A 12
6 2017-06-01 A 9.0
7 2017-01-01 B 12.5
8 2017-02-01 B 13.3
9 2017-03-01 B 14.8
10 2017-04-01 B 11
11 2017-05-01 B 10
12 2017-06-01 B 12.1
13 2017-01-01 C 13
14 2017-02-01 C 12.2
15 2017-03-01 C 11
16 2017-04-01 C 10.9
17 2017-05-01 C 13.4
18 2017-06-01 C 11.1
I need to forecast multiple univariate time series models (ets, auto.arima and prophet) by groups (A, B, C). Assume the groups are independent of each other.Also how can we extract error metrics and point forecasts say 2 period ahead (in a data frame) and plot the forecasts, again grouped by groups.Need help here!!!
Iterative methods like using packages such as tidyverse/purrr, or sweep etc. may be a solution here. ?
First convert the dates to yearmon
class in order that the months be regularly spaced since Dates are not due to the different number of days per month. yearmon
represents dates internally as year + 0 for Jan, year + 1/12 for Feb, ..., year + 11/12 for Dec. If desired the Date can subsequently be converted from yearmon
to numeric using as.numeric
to get the internal represntation.
calc
represents the function that performs the calculation on a single group. Replace it with your function. Its first argument should be a data frame with Date
and Amount
columns. Additional arguments are optional and only needed if it is desired to pass fixed parameters that do not vary across groups. In the example below we pass a string, "Hello"
to the msg
argument. The function can return any sort of object such as a plain vector, list or other object.
In the last line by
will call calc
, once per group, returning a list of the return values from calc
, one component per group.
library(zoo)
data2 <- transform(data,
Date = as.yearmon(Date),
Amount = as.numeric(Amount)
)
calc <- function(dat, msg) {
print(msg)
fm <- lm(Amount ~ Date, dat)
predict(fm, list(Date = tail(dat$Date, 1) + 2/12))
}
by(data2[-2], data2[[2]], calc, msg = "Hello")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.