如何在R中处理错误“Error in eval(predvars, data, env) : numeric 'envir' arg not of length one”?
当我们没有将自变量作为数据框传递时,就会发生此错误。predict 函数将根据提供的自变量值预测因变量的值,我们还可以使用创建模型所用的自变量值。
示例
考虑以下数据框 -
set.seed(1) x <-rnorm(20) y <-runif(20,5,10) df <-data.frame(x,y) df
输出
x y 1 -0.62645381 9.104731 2 0.18364332 8.235301 3 -0.83562861 8.914664 4 1.59528080 7.765182 5 0.32950777 7.648598 6 -0.82046838 8.946781 7 0.48742905 5.116656 8 0.73832471 7.386150 9 0.57578135 8.661569 10 -0.30538839 8.463658 11 1.51178117 7.388098 12 0.38984324 9.306047 13 -0.62124058 7.190486 14 -2.21469989 6.223986 15 1.12493092 5.353395 16 -0.04493361 5.497331 17 -0.01619026 6.581359 18 0.94383621 7.593171 19 0.82122120 8.310025 20 0.59390132 7.034151
创建线性模型 -
M <-lm(y~x,data=df)
导致错误的预测公式 -
predict(M,newdata=df$x,interval="confidence") Error in eval(predvars, data, env) : numeric 'envir' arg not of length one
不会导致错误的预测公式 -
predict(M,newdata=data.frame(df$x),interval="confidence")
输出
fit lwr upr 1 7.642084 6.814446 8.469722 2 7.536960 6.927195 8.146725 3 7.669228 6.738695 8.599762 4 7.353775 6.214584 8.492966 5 7.518031 6.900897 8.135166 6 7.667261 6.744547 8.589975 7 7.497538 6.854767 8.140310 8 7.464980 6.749018 8.180943 9 7.486073 6.821666 8.150480 10 7.600420 6.902430 8.298410 11 7.364611 6.273305 8.455917 12 7.510202 6.885355 8.135048 13 7.641408 6.816180 8.466635 14 7.848187 6.091378 9.604995 15 7.414811 6.530792 8.298831 16 7.566622 6.935903 8.197340 17 7.562892 6.936919 8.188865 18 7.438312 6.639516 8.237107 19 7.454223 6.706932 8.201514 20 7.483722 6.814287 8.153156
如果我们想根据自变量预测因变量,我们也可以简单地使用 Model 对象
示例
predict(M)
输出
1 2 3 4 5 6 7 8 7.642084 7.536960 7.669228 7.353775 7.518031 7.667261 7.497538 7.464980 9 10 11 12 13 14 15 16 7.486073 7.600420 7.364611 7.510202 7.641408 7.848187 7.414811 7.566622 17 18 19 20 7.562892 7.438312 7.454223 7.483722
示例
predict(M,interval="confidence")
输出
fit lwr upr 1 7.642084 6.814446 8.469722 2 7.536960 6.927195 8.146725 3 7.669228 6.738695 8.599762 4 7.353775 6.214584 8.492966 5 7.518031 6.900897 8.135166 6 7.667261 6.744547 8.589975 7 7.497538 6.854767 8.140310 8 7.464980 6.749018 8.180943 9 7.486073 6.821666 8.150480 10 7.600420 6.902430 8.298410 11 7.364611 6.273305 8.455917 12 7.510202 6.885355 8.135048 13 7.641408 6.816180 8.466635 14 7.848187 6.091378 9.604995 15 7.414811 6.530792 8.298831 16 7.566622 6.935903 8.197340 17 7.562892 6.936919 8.188865 18 7.438312 6.639516 8.237107 19 7.454223 6.706932 8.201514 20 7.483722 6.814287 8.153156
广告