2016-12-05 81 views
-1

我已經在這裏讀了幾個答案,但我恐怕我一直無法找出答案。R警告:newdata'有15行,但發現變量有22行

我的R代碼裏面是:

colors <- bmw[bmw$Channel=="Colors" & bmw$Hour=20,] 
colors_test <- tail(colors, 89) 
colors_train <- head(colors, 810) 

colors_train_agg <- aggregate(colors_train$Impressions, list(colors_train$`Position of Ad in Break`), FUN=mean, na.rm=TRUE) 
colnames(colors_train_agg) <- c("ad_position", "avg_impressions") 
lm_colors <- lm(colors_train_agg$avg_impressions ~ poly(colors_train_agg$ad_position, 12)) 
summary(lm_colors) 

colors_test_agg <- aggregate(colors_test$Impressions, list(colors_test$`Position of Ad in Break`), FUN=mean, na.rm=TRUE) 
colnames(colors_test_agg) <- c("ad_position", "avg_impressions") 
new.df <- data.frame(colors_test_agg$ad_position) 
colnames(new.df) <- c("ad_position") 
colors_test_test <- predict(lm_colors, newdata=new.df) 

所以我有完全針對訓練和測試數據的列名相同。我仍然得到警告:

Warning message: 'newdata' had 15 rows but variables found have 22 rows

有一個人提出什麼是錯的?另外,我想知道我是否以正確的方式進行。

此外,有關如何計算模型的準確性的一些指針將不勝感激。謝謝!

+2

喜歡'LM(avg_impressions〜聚(ad_position,12),數據= colors_train_agg) –

+0

由於問題是關於行不一致的問題,如果您提供了一些維度,它會有所幫助。 'lapply(list(colors_test,colors_train,colors_train_agg,colors_test_agg),dim)' –

+0

你能提供這些數據嗎? –

回答

5

解決方案:

lm_colors <- lm(avg_impressions ~ poly(ad_position, 13), data=colors_train_agg) 

原因: 如何model.matrix()生成矩陣內線得分predict()數據你可以比較自己。所以當我們通過model(df$var1~df$var2)時,model.matrix()尋找df$var1df$var2來生成矩陣 - 但是這具有訓練數據(df)的維度。在modelnewdata

經過下面的步驟(如果你有興趣知道的原因),具有不同名稱的問題:

model1 <- lm(var1~var2, data = df) 
model2 <- lm(df$var1~df$var2) 
debug(predict) 
predict(model1, newdata = df1) 
predict(model2, newdata = df1)