简体   繁体   中英

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:

r = lm(dollar_value ~ GDPPC, prices_gdp)

( prices_gdp is a data.table , if that matters).

I can now easily generate a bunch of values based on a data.table using predict . 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

predict(r, 0)

This gives me an error: 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?

You can just create the same data table and put the regressor GDPPC to zero. 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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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