使用函数均值 [R] 时出现"argument is not numeric or logical: returning NA"错误



我使用Ames数据集创建了以下代码:

NbrMLR <- lm(SalePrice ~ Neighborhood, data = ames_housing_data)
pred <- as.data.frame(predict(NbrMLR, ames_housing_data))
library(reshape)
pred <- rename(pred,c('predict(NbrMLR, ames_housing_data)' = 'prd'))
ames_housing_data$NbrPred <- pred
ames_housing_data$NbrRes <- SalePrice - ames_housing_data$NbrPred
ames_housing_data$absoluteNbrRes <- abs(ames_housing_data$NbrRes)
NbrMAE <- mean(ames_housing_data$absoluteNbrRes)

此代码导致以下错误:

参数不是数字或逻辑:返回NA

str(ames_housing_data$absoluteNbrRes)告诉我有一个变量类型为$ prd: num的数据帧。虽然我熟悉num,但我以前从未听说过prd: num。这会引起问题吗?为什么mean()不作用于在我看来是有效向量的东西?

ames_housing_data$NbrPred <- pred[[1]]将修复它。

关于您的错误:prd是一个变量名(正如您所定义的!(。您将数据帧传递给mean,这会导致错误。


如果我是你,我会写以下代码:

NbrMLR <- lm(SalePrice ~ Neighborhood, data = ames_housing_data)
ames_housing_data$NbrPred <- predict(NbrMLR, ames_housing_data)
ames_housing_data$NbrRes <- SalePrice - ames_housing_data$NbrPred
ames_housing_data$absoluteNbrRes <- abs(ames_housing_data$NbrRes)
NbrMAE <- mean(ames_housing_data$absoluteNbrRes)

相关内容

最新更新