【问题标题】:Why does predict() require me to attach()?为什么 predict() 需要我 attach()?
【发布时间】:2016-02-03 11:59:02
【问题描述】:

我一直在做一个教科书问题,要求我确定某个 x 的 95% 置信区间。这本书附带了一张 R 手册复制表,但它告诉我要 attach() 数据框。我知道您不应该使用 attach()(请参阅:http://www.r-bloggers.com/to-attach-or-not-attach-that-is-the-question/)。因此,我一直将变量名称直接列为 DataFrame$Variable,并且在我开始使用 predict() 之前它运行良好。 如果我按照教科书的 r 说明手册进行操作,会发生以下情况:

> attach(TextPrices)
> new.data <- data.frame(Pages=450)
> TextPrices.lm1 <- lm(Price ~ Pages)
> predict(TextPrices.lm1, new.data, int="confidence")
       fit      lwr      upr
1 62.87549 51.73074 74.02024
> predict(TextPrices.lm1, new.data, int="prediction")
       fit       lwr      upr
1 62.87549 0.9035981 124.8474

这是完美的。也与我在谷歌上发现的相同问题相匹配(http://www.r-tutor.com/elementary-statistics/simple-linear-regression/confidence-interval-linear-regression)。但是,使用 DataFram$Variable 会搞砸一切,我不知道为什么。

> TextPrices.lm1 <- lm(TextPrices$Price ~ TextPrices$Pages)
> new.data <- data.frame(TextPrices$Pages = 450)
Error: unexpected '=' in "new.data <- data.frame(TextPrices$Pages ="
> new.data <- data.frame(Pages = 450)
> predict(TextPrices.lm1, new.data, interval="confidence")

上面的代码给了我 30 行 fit、lwr 和 upr。附带警告消息:

Warning message:
'newdata' had 1 row but variables found have 30 rows 

我很确定问题出在我输入代码的方式上,不知道是怎么回事。

【问题讨论】:

  • 这不是因为您附加或不附加数据。问题是,在您未附加的尝试中,当您制作new.data 时,您是在告诉 R 将 TextPrices$Pages 的值设置为 450。将其替换为“Pages”,就像您在附加示例中所做的那样,并且你会没事的。
  • 将其更改为页面并不能解决问题。我已经尝试过了,它只会产生同样的问题。
  • TextPrices 来自什么包?
  • 这是一个受版权保护的数据集。实际上它是 2 列(价格、页数),有 30 行显示每本书的价格和它有多少页。置信区间适用于 450 页的书。
  • 从不attach。不必要时不要使用data$column(例如,当有数据参数时,在lm 中)。

标签: r


【解决方案1】:

制作一个数据框,因为你的显然是机密的,我们可以从以下开始:

text_prices <- data.frame(pages = round(runif(30, 100, 600), 0), 
                          price = round(runif(30, 10, 120), 2))

接下来,我们尝试按照您的方式制作模型:

text_prices.lm1 <- lm(text_prices$price ~ text_price$pages)
new_data <- data.frame(pages = 450)
predict(text_prices.lm1, new_data, interval = "confidence")
#         fit      lwr       upr
# 1  81.56752 58.11610 105.01894
# 2  75.35715 61.54237  89.17193
# 3  72.56597 58.21001  86.92194
# .
# .
# .
# 29 79.96259 59.83313 100.09205
# 30 74.76402 61.16544  88.36261
# Warning message:
# 'newdata' had 1 row but variables found have 30 rows

同样的错误。因此,考虑到它在我们附加数据时有效,但不是现在,问题可能来自我们将数据输入到lm 不正确的事实。让我们换一种方式试试:

text_prices.lm1 <- lm(data = text_prices, price ~ pages)
new_data <- data.frame(pages = 450)
predict(text_prices.lm1, new_data, interval = "confidence")
#        fit      lwr      upr
# 1 78.46233 61.06646 95.85821

我不完全确定为什么这会修复解决方案,但这是您无需 attach 数据即可解决问题的方式。

【讨论】:

  • 成功了。我很困惑为什么这可以解决问题。不过还是谢谢你。
猜你喜欢
  • 2019-06-09
  • 2012-05-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-23
  • 2021-07-01
  • 2014-06-18
  • 2017-02-26
相关资源
最近更新 更多