简体   繁体   中英

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!

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

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"))

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