【问题标题】:how do you run predict on time series data?您如何对时间序列数据进行预测?
【发布时间】:2015-04-24 22:17:29
【问题描述】:

我正在尝试根据时间序列数据创建预测。

我的数据框调用 dat 如下所示:

输入(头部(dat))

dat <- structure(list(out = c(5, 0, 0, 0, 0, 0), Date = c(1423825200000, 
1423825500000, 1423825800000, 1423826100000, 1423826400000, 1423826700000
)), .Names = c("out", "Date"), row.names = c(NA, 6L), class = "data.frame")

目前我的数据框 dat 中有 81 行。我的列被调用并且日期,日期列在纪元中。

我需要先建立一个线性模型:

 lin <- lm(dat[,1]~dat[,2], data=dat)

基于这个模型,我需要预测 7 天的每小时数据点等,所以我这样做:

t<-3600
newdata <- seq(tail(dat$Date,1), tail(dat$Date,1)+604800, t)
newdata<-data.frame(newdata)
    colnames(newdata)<-c("Date")
    predictions <- predict(lin, newdata=newdata, level=0.95, interval="prediction")
    predictions <- data.frame(predictions)
    f<-predictions
    f<-data.frame(f)
    f<-cbind(f, newdata)
    f<-f[,c("fit", "Date")]
    colnames(f)<-c("Forecast", "Date")

我收到此错误:

Error in data.frame(..., check.names = FALSE) : 
  arguments imply differing number of rows: 81, 169 In addition: Warning message:
'newdata' had 169 rows but variables found have 81 rows

无论我的数据框 (dat) 的大小如何,我都应该能够建立一个线性模型,并且基于 newdata,我应该执行预测函数。有什么想法吗?

【问题讨论】:

  • 也许你的一些变量是在lm中扩展的因子
  • @kristang,它们是数字。
  • 尝试使用公式lin &lt;- lm(out~Date, data=dat)中的变量名称
  • @NicE,它有效,但它是否重要。我希望能够通过 R 包中的一个函数来做到这一点,我需要一切都是动态的。恐怕,对名称发出 lm 函数可能会引发一些其他问题等。
  • @user1471980 我也许能帮到你。请告诉我你的训练的暗淡和你的测试集的暗淡。请告诉我您是否正在构建 OLS(只有一个变量对一个变量)?还是做其他事情?

标签: r time-series predict


【解决方案1】:

试试这个。这样,您仍然可以保持一切动态。

variable.list<-names(dat)
lin <- lm(as.formula(paste(variable.list[1],variable.list[2], sep="~") ), data=dat)

让我知道它是否有效

【讨论】:

  • 这里发生的情况是,在您的原始代码中,您在线性模型中使用的两个变量称为 dat[,1] 和 dat[,2],而不是“out”和“Date ”。您可以通过 names(lin$coefficients) 检查名称。因此,预测无法以正确的方式将线性模型与您的新数据集关联起来。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-07
  • 2021-12-21
  • 2020-03-03
  • 2017-11-22
  • 2023-03-11
  • 2016-04-10
相关资源
最近更新 更多