Predict y value for a given x in R

17,928

Solution 1

If your purposes are related to just one prediction you can just grab your coefficient with

coef(mod)

Or you can just build a simple equation like this.

coef(mod)[1] + "Your_Value"*coef(mod)[2]

Solution 2

Its usually more robust to use the predict method of lm:

f2<-data.frame(age=c(10,20,30),weight=c(100,200,300))
f3<-data.frame(age=c(15,25))
mod<-lm(weight~age,data=f2)
pred3<-predict(mod,f3)

This spares you from wrangling with all of the coefs when the models can be potentially large.

Share:
17,928
Erica
Author by

Erica

Updated on June 25, 2022

Comments

  • Erica
    Erica almost 2 years

    I have a linear model:

    mod=lm(weight~age, data=f2)
    

    I would like to input an age value and have returned the corresponding weight from this model. This is probably simple, but I have not found a simple way to do this.

  • gosuto
    gosuto over 4 years
    Is this truly the most concise way to do this? Can predict() not do this, without creating a whole new data.frame?