gpt4 book ai didi

R:在predict()中数字 'envir' arg的长度不是1

转载 作者:行者123 更新时间:2023-12-02 01:25:56 24 4
gpt4 key购买 nike

我尝试使用 predict() 函数通过将变量传递到模型中来预测 R 中的值。

我收到以下错误:

Error in eval(predvars, data, env) : 
numeric 'envir' arg not of length one

这是我的数据框,名称 df:

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)

> model

Call:
lm(formula = df$Total ~ df$Coupon)

Coefficients:
(Intercept) df$Coupon
107286259 1349

现在,当我运行 predict 时,我收到上面显示的错误。

> predict(model, df$Total, interval="confidence")
Error in eval(predvars, data, env) :
numeric 'envir' arg not of length one

知道我哪里出错了吗?

谢谢

最佳答案

这里有几个问题:

  1. predict()newdata 参数需要一个预测器变量。因此,您应该向其传递Coupon 值,而不是Total,它是模型中的response 变量。

  2. 预测变量需要作为数据框中的命名列传入,以便predict() 知道它所收到的数字代表什么。 (当您考虑具有多个预测变量的更复杂的模型时,这一点的必要性就变得很明显)。

  3. 为此,您的原始调用应通过 data 参数传递 df,而不是直接在公式中使用它。 (这样,newdata 中的列名称将能够与公式右侧的名称相匹配)。

合并这些更改后,这将起作用:

model <- lm(Total ~ Coupon, data=df)
new <- data.frame(Coupon = df$Coupon)
predict(model, newdata = new, interval="confidence")

关于R:在predict()中数字 'envir' arg的长度不是1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9026383/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com