I have data that looks like the following:
df <- structure(list(Variable =c("A", "B", "A", "B", "A", "B", "A", "B", "A"),
Quantity=c("1", "100", "2", "5", "6", "30", "8", "15", "133"),
YearQuarter=c("2017Q2", "2017Q2", "2017Q3", "2017Q3", "2017Q4", "2017Q4", "2018Q1", "2018Q1", "2018Q2"),
Week=c("1", "10", "1", "2", "1", "6", "2", "9", "13")),
class= "data.frame", row.names=c(NA, -9L))
There are no actual dates but I would like to turn it into a time series data set so I can forecast. The format of the time series is week 1-13 for each year/qtr. Ideally, I can get this to a 52-week frequency so I can forecast the following 52 weeks for each forecast.
It's unclear what you want as a result but if we assume that df
represents two series A
and B
and you want a regularly spaced ts
series of frequency 52 as a result then use the following.
library(zoo)
df2 <- transform(df, Quantity = as.numeric(Quantity))
toTime <- function(yq, wk) as.numeric(as.yearqtr(yq)) + (as.numeric(wk) - 1)/13/4
z <- read.zoo(df2, index = c("YearQuarter", "Week"), split = "Variable", FUN = toTime)
tt <- as.ts(z)
frequency(tt)
## [1] 52
If you want to treat Variable
as a series of 1's and 2's (for A
and B
respectively):
df3 <- transform(df, Quantity = as.numeric(Quantity),
Variable = match(Variable, c("A", "B")))
z3 <- read.zoo(df3, index = c("YearQuarter", "Week"), FUN = toTime)
tt3 <- as.ts(z3)
Note that most time series forecasting routines require regularly spaced non-missing data and the data shown in the question will generate many NAs when regularly spaced.
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.