DSUR
DSUR

Reputation: 43

Pulling variables from lm in R to use predict

Say I run the following lm

my.model = lm(distance ~ speed, data = my.data)

I could do the following to do a one element prediciton

predict(my.model, speed = c(40))

Here is the situation: I have a lm and I know what it does (that it was regression of distance on speed) but I didn't know that the regressor was named speed. How can I still do predict?

predict(my.model, ??? = c(40))

I could get the name of the regressor by names(my.model$coefficients) but I can't figure out how to pass it into predict

predict(my.model, names(my.model$coefficients)[2] = c(40)) won't work

Any suggestions?

Thanks!

Upvotes: 2

Views: 164

Answers (2)

G. Grothendieck
G. Grothendieck

Reputation: 270348

Using the builtin BOD for the example run lm and then pass a one element list or data frame to predict using setNames to set the name appropriately:

fm <- lm(demand ~ Time, BOD)

predict(fm, setNames(list(5.5), variable.names(fm)[2]))
##        1 
## 17.98929 

A different approach is not to use predict at all. Using fm from above:

coef(fm) %*% c(1, 5.5)
##          [,1]
## [1,] 17.98929

Upvotes: 5

catastrophic-failure
catastrophic-failure

Reputation: 3905

Using iris as an example

myModel = lm(Petal.Width ~ Sepal.Length, data = iris)
predict(myModel, structure(list(1), .Names = attr(terms(myModel), "term.labels"), class = "data.frame"))
#        1 
#-2.447297 

Explanation

The independent variable name in myModel is recovered using:

attr(terms(myModel), "term.labels")
#[1] "Sepal.Length"

If we want to dynamically create a data.frame with a column named as the independent variable in myModel, we do:

structure(list(1), .Names = attr(terms(myModel), "term.labels"), class = "data.frame")
#  Sepal.Length
#1            1

Then we pass that data.frame to the predict method for lm objects using:

predict(myModel, structure(list(1), .Names = attr(terms(myModel), "term.labels"), class = "data.frame"))

Upvotes: 1

Related Questions