我还是R的新手,我正面临一个我无法解决的问题。
我想预测我的时间序列数据。 我有今年的每日数字:y和去年的每日数字,我想用它作为预测器。 数字显示周周期。我试过这段代码。 (为清晰起见假号)
x = rnorm(60,0,1)
y = rnorm(60,0 ,1) + 2*cos(2*pi*1:60/7) + 10*x
new_x = rnorm(10,0,1)
y <- ts(y,frequency = 7)
fit <- tslm(y ~ trend + season + x)
fcast = forecast.lm(fit, h = 10, newdata = new_x)
我收到错误消息:
Error in model.frame.default(Terms, newdata, na.action = na.action, xlev = object$xlevels) :
variable lengths differ (found for 'x')
In addition: Warning message:
'newdata' had 10 rows but variables found have 60 rows
我做错了什么提示?
答案 0 :(得分:4)
来自fit
对象:
Call:
lm(formula = formula, data = "y", na.action = na.exclude)
Coefficients:
(Intercept) trend season2 season3 season4 season5 season6 season7 x
1.1644029 0.0009672 -1.5575562 -3.6723105 -3.1824001 -1.5658857 0.0789683 0.3053541 9.9233635
最后一个变量名为x
。 forecast.lm
的帮助说newdata
是一个可选的data.frame。您需要将new_x
转换为data.frame,并将x
作为列名。
library(forecast)
x = rnorm(60,0,1)
y = rnorm(60,0 ,1) + 2*cos(2*pi*1:60/7) + 10*x
new_x = rnorm(10,0,1)
y <- ts(y,frequency = 7)
fit <- tslm(y ~ trend + season + x)
# You can directly use `forecast`, as `fit` is an lm object
# and you don't need `h`, as you provide new data.
fcast = forecast(fit, newdata = data.frame(x=new_x))
# Point Forecast Lo 80 Hi 80 Lo 95 Hi 95
# 9.571429 -3.1541222 -4.5886075 -1.719637 -5.37216743 -0.9360771
# 9.714286 12.5962250 11.1367496 14.055700 10.33953926 14.8529108
# 9.857143 10.5924632 9.1480030 12.036924 8.35899443 12.8259321
#10.000000 15.9419378 14.4775444 17.406331 13.67764776 18.2062278
#10.142857 -7.1887433 -8.6444741 -5.733013 -9.43963897 -4.9378477
#10.285714 -9.4133170 -10.8470152 -7.979619 -11.63014523 -7.1964887
#10.428571 2.2702132 0.8331488 3.707278 0.04818005 4.4922464
#10.571429 0.3519401 -1.1037991 1.807679 -1.89896851 2.6028487
#10.714286 -11.8348209 -13.2930857 -10.376556 -14.08963475 -9.5800070
#10.857143 1.0058209 -0.4435763 2.455218 -1.23528154 3.2469233
答案 1 :(得分:0)
您可以将new_x转换为data.frame,您的初始代码也可以正常工作。
new_x变量的类型为number,需要将data.frame作为forecast.lm的输入。
此致
Ganesh Bhat
答案 2 :(得分:-1)
错误似乎很明显:
new_data有10个随机变量,而y&amp; x有60.你能更新new_data有60个随机变量并验证错误没有发生吗?
此致
内甚