代码之家  ›  专栏  ›  技术社区  ›  analyticsPierce

如何将日期和预测添加到data.frame?

r
  •  4
  • analyticsPierce  · 技术社区  · 14 年前

    我有一个data.frame,它包含了几个月来每天的历史数据。我想在这个data.frame的末尾添加一个预测。

    例如,我可以运行以下命令来创建一个简单的示例data.frame。

    months <- c("2010-10-17","2010-10-18","2010-10-19","2010-10-20")
    revenue <- c(10000,11000,10500,9500)
    
    results <- data.frame(months,revenue)
    

    并运行此函数生成预测。

    forecast(results$revenue)
    

    我一直坚持的是如何为10月的剩余时间添加日期序列,并包括来自预测的正确值。我想生成类似这样的结果,将30天的预测添加到历史数据中。

    > 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
    

    感谢您的帮助。谢谢。

    1 回复  |  直到 14 年前
        1
  •  2
  •   Matt Parker    14 年前

    这几乎肯定不是实现这一目标的理想方式,但它将使您达到目标:

    #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)
    

    这被分成了比你需要的更多的步骤,但这样读起来更容易。希望这有帮助。