代码之家  ›  专栏  ›  技术社区  ›  Yehuda

“参数不是数字或逻辑的:使用函数mean[r]时返回na”错误

  •  2
  • Yehuda  · 技术社区  · 6 年前

    我用了 Ames data set 创建以下代码:

    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() 根据我认为有效的向量来行动?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Zheyuan Li    6 年前

    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)