Reputation: 5588
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?
Upvotes: 1
Views: 5036
Reputation: 61983
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
Upvotes: 0
Reputation: 8374
You can just create the same data table and put the regressor GDPPC to zero. Try:
predict(r, data.frame(GDPPC = 0))
Upvotes: 5