简体   繁体   English

如何从R中的线性回归预测单个值?

[英]How can I predict a single value from a linear regression in R?

I've made a linear regression of dollar prices to GDPPC like so: 我将美元价格与GDPPC进行了线性回归,如下所示:

r = lm(dollar_value ~ GDPPC, prices_gdp)

( prices_gdp is a data.table , if that matters). (如果重要, prices_gdp是一个data.table )。

I can now easily generate a bunch of values based on a data.table using predict . 现在,我可以使用predict轻松地基于data.table生成一堆值。 But what I want to do (in order to plot a geom_abline on a chart) is calculate the dollar value when GDPPC is zero, and get that back as a number—something like 但是我想要做的(为了在图表上绘制geom_abline )是在geom_abline为零时计算美元值,然后将其取回为数字, 就像

predict(r, 0)

This gives me an error: Error in eval(predvars, data, env): object 'GDPPC' not found . 这给了我一个错误: Error in eval(predvars, data, env): object 'GDPPC' not found的错误: Error in eval(predvars, data, env): object 'GDPPC' not found Is there any way of doing this short of creating a new dummy data.table with GDPPC=0 as its only row, feeding it in, and then pulling the number out? 除了创建一个新的虚拟数据表( data.table = 0作为唯一行),将其输入然后将其取出来之外,还有什么办法可以做到?

You can just create the same data table and put the regressor GDPPC to zero. 您可以只创建相同的数据表,并将回归器GDPPC设置为零。 Try: 尝试:

predict(r, data.frame(GDPPC = 0))

You could create a function which extracts the name of the term in the model and makes the call to predict for you. 您可以创建一个函数,该函数提取模型中术语的名称并进行调用以为您预测。

preds <- function(o, vals){
  #' Make prediction from simple linear regression
  #'
  #' Makes a prediction from a simple linear regression without
  #' needing to manually create a data.frame.  This will fail
  #' on models with more than one predictor.
  #' @param o The lm object to use to make predictions
  #' @param vals The values to make predictions for.
  dat <- setNames(data.frame(vals), as.character(formula(o)[[3]]))
  predict(o, newdata = dat)
}

and using it... 并使用它...

> o <- lm(mpg ~ wt, data = mtcars)
> preds(o, 1:3)
       1        2        3 
31.94065 26.59618 21.25171 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM