【发布时间】:2012-02-20 04:03:04
【问题描述】:
我 posted earlier today 关于使用 predict 函数时遇到的错误。我能够得到纠正,并认为我走在正确的道路上。
我有许多观察结果(实际值),并且我有一些数据点要外推或预测。我使用lm 创建模型,然后尝试使用predict 与将用作预测器输入的实际值。
这段代码在我之前的帖子中都是重复的,但这里是:
df <- read.table(text = '
Quarter Coupon Total
1 "Dec 06" 25027.072 132450574
2 "Dec 07" 76386.820 194154767
3 "Dec 08" 79622.147 221571135
4 "Dec 09" 74114.416 205880072
5 "Dec 10" 70993.058 188666980
6 "Jun 06" 12048.162 139137919
7 "Jun 07" 46889.369 165276325
8 "Jun 08" 84732.537 207074374
9 "Jun 09" 83240.084 221945162
10 "Jun 10" 81970.143 236954249
11 "Mar 06" 3451.248 116811392
12 "Mar 07" 34201.197 155190418
13 "Mar 08" 73232.900 212492488
14 "Mar 09" 70644.948 203663201
15 "Mar 10" 72314.945 203427892
16 "Mar 11" 88708.663 214061240
17 "Sep 06" 15027.252 121285335
18 "Sep 07" 60228.793 195428991
19 "Sep 08" 85507.062 257651399
20 "Sep 09" 77763.365 215048147
21 "Sep 10" 62259.691 168862119', header=TRUE)
str(df)
'data.frame': 21 obs. of 3 variables:
$ Quarter : Factor w/ 24 levels "Dec 06","Dec 07",..: 1 2 3 4 5 7 8 9 10 11 ...
$ Coupon: num 25027 76387 79622 74114 70993 ...
$ Total: num 132450574 194154767 221571135 205880072 188666980 ...
代码:
model <- lm(df$Total ~ df$Coupon, data=df)
> model
Call:
lm(formula = df$Total ~ df$Coupon)
Coefficients:
(Intercept) df$Coupon
107286259 1349
预测代码(基于之前的帮助):
(这些是我想用来获取预测值的预测值)
Quarter = c("Jun 11", "Sep 11", "Dec 11")
Total = c(79037022, 83100656, 104299800)
Coupon = data.frame(Quarter, Total)
Coupon$estimate <- predict(model, newdate = Coupon$Total)
现在,当我运行它时,我收到以下错误消息:
Error in `$<-.data.frame`(`*tmp*`, "estimate", value = c(60980.3823396919, :
replacement has 21 rows, data has 3
我用来构建模型的原始数据框中有 21 个观察值。我现在正在尝试根据模型预测 3 个值。
我要么没有真正理解这个函数,要么我的代码有错误。
我们将不胜感激。
谢谢
【问题讨论】:
-
您几乎可以肯定需要使用
data参数到lm以使其工作,即model <- lm(Total ~ Coupon, data=df)。那我建议Coupon$estimate <- predict(model, newdata = Coupon)$Total -
@BenBolker 我同意第一部分,但不太确定第二部分。我认为
predict(model, newdata = Coupon)应该是他想要的。 -
@joran 是的,我认为你是对的。
-
@BenBolker & @joran 更新了代码以反映 Ben 建议的
data=df。结果相同。然后我将其更新为 joran 的建议。同样的错误。 -
您没有按照 Ben 的说明进行更新。注意到您的配方规格有所不同了吗?
df$Total与Total相比。你的方式,当你使用predict时,它会寻找一个名为df$Coupon的变量,而不仅仅是Coupon(我认为)。至少,名字不匹配。