我posted earlier today關於我使用predict
函數得到的錯誤。我得以糾正,並認爲我走在了正確的道路上。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)
現在,當我跑,我得到這個錯誤信息:
,我用來建立模型,它有21個觀測Error in `$<-.data.frame`(`*tmp*`, "estimate", value = c(60980.3823396919, :
replacement has 21 rows, data has 3
我原來的數據幀。我現在試圖根據模型預測3個值。
我要麼不真正理解這個函數,要麼在我的代碼中有錯誤。
幫助,將不勝感激。
感謝
你幾乎肯定需要用'data'參數'lm'噸得到這個工作,即'模型< - LM(總共〜優惠券,data = df)'。然後,我會建議'優惠券$估計< - 預測(模型,newdata =優惠券)$總計' – 2012-01-27 03:46:30
@BenBolker我同意第一部分,不太確定第二部分。我認爲'預測(模型,新數據=優惠券)'應該是他想要的。 – joran 2012-01-27 03:50:26
@joran是的,我認爲你是對的。 – 2012-01-27 03:51:18