开发者

How can I add dates and forecast to data.frame?

开发者 https://www.devze.com 2023-01-20 16:57 出处:网络
I have a data.frame that contains historic data by day for several months. I would like to add a forecast to the end of this data.frame.

I have a data.frame that contains historic data by day for several months. I would like to add a forecast to the end of this data.frame.

For example, I can run the following to create a simple example data.frame.

months <- c("2010-10-17","2010开发者_如何学C-10-18","2010-10-19","2010-10-20")
revenue <- c(10000,11000,10500,9500)

results <- data.frame(months,revenue)

And run this function to generate the forecast.

forecast(results$revenue)

What I am stuck on is how to add a date sequence for the rest of October and include the correct values from the forecast. I want to generate something that looks like this, adding 30 days of forecast to the historic data.

> print(results)
       months revenue
1  2010-10-17   10000
2  2010-10-18   11000
3  2010-10-19   10500
4  2010-10-20    9500
5  2010-10-21   10250
6  2010-10-22   10250
7  2010-10-23   10250
8  2010-10-24   10250
9  2010-10-25   10250
10 2010-10-26   10250
11 2010-10-27   10250
12 2010-10-28   10250
13 2010-10-29   10250
14 2010-10-30   10250
15 2010-10-31   10250


This is split out into more steps than you need, but it's easier to read that way:

#Get the sequence from a date to another date
date.seq <- as.Date("2010-10-17"):as.Date("2010-10-31")

#Unfortunately, add.dates is numeric - but can easily be converted back to
#dates if you know the origin (which you can find at ?Date)
new.dates <- data.frame(months = as.Date(date.seq, origin = "1970-01-01"),
                        revenue = NA)

#Slap it on to your existing dates
results.fc <- rbind(results, new.dates)
0

精彩评论

暂无评论...
验证码 换一张
取 消