Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

r - Add months of zero demand to zoo time series

I have some intermittent demand data that only includes lines where demand is present. I bring it in via read.csv, and my 2 columns are Date (as date) and Quantity (as integer). Then I convert it to a zoo series and combine the daily demand into monthly demand. My final output is a zoo series with the date being the first day of the month and the summed demand for that month.

My problem is that this zoo series is missing the in between months that have zero demand and I need these to forecast intermittent demand correctly.

For example: I have quantity 2 in date 2013-01-01 and then the next line is quantity 3 in 2013-10-01. I need to add quantity zero to 2013-02-01 through 2013-09-01.

Date <- c('1/1/2013','10/1/2013','11/1/2013')
Quantity <- c('2','3','6')

Date <- as.Date(Date, "%m/%d/%Y")

df <- data.frame(Date, Quantity)
df <- read.zoo(df)
df

The zoo series output:

2013-01-01  2013-10-01  2013-11-01
         2           3           6
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Because "df" is a zoo object, you may use merge.zoo and its fill argument. The current data set is merged with an empty zoo object which contains all the desired dates.

tt <- seq(min(Date), max(Date), "month")
merge(df, zoo(, tt), fill = 0)

# 2013-01-01 2013-02-01 2013-03-01 2013-04-01 2013-05-01 2013-06-01 2013-07-01 2013-08-01 2013-09-01 2013-10-01 2013-11-01 
#          2          0          0          0          0          0          0          0          0          3          6 

For further examples, see ?merge.zoo ("extend an irregular series to a regular one").


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...