简体   繁体   中英

How to get lm object from list of coefficients and intercept in R

I have a list of coefficients with intercept and I would like to create a R lm object from these. Is that possible and if so, how?

We can use y = intercept + slope * x if we know intercept and slope and x is some value for which we want to know y. (If we have more than one predictor it works similarly.)

The above is so simple we don't really need an lm object to do it but if you really want an lm object anyways then since a line is determined by two points we can use these two which follow from the equation above.

  • x = 0, y = intercept
  • x = 1, y = intercept + slope

so using those fm below is the required lm object. (If we have multiple predictors then consider the point where they are all 0 and the points where exactly one of them is 1 and the rest are 0.)

intercept <- 1; slope <- 2 # test data

y <- c(intercept, intercept + slope)
x <- 0:1

fm <- lm(y ~ x)

coef(fm)
## (Intercept)          x1          x2 
##           1           2           3 

# suppose we want to know y given x = 3. Here are two ways.

predict(fm, list(x = 3))
## 1 
## 7 

intercept + slope * 3
## [1] 7

Here is an example with multiple predictors:

b <- 1:3 # test data

# 1st row of X is all 0's; remaining rows each have one 1 and rest 0    
X <- diag(length(b))[, -1]
colnames(X) <- paste0("x", seq(ncol(X))) # x1, x2
y <- b[1] + c(0, b[-1])    
DF <- data.frame(y, X)
fm <- lm(y ~ ., DF)

predictors <- c(x1 = 3, x2 = 10)

predict(fm, as.list(predictors))
##  1 
## 37 

sum(b * c(1, predictors))
## [1] 37

Updated

Have updated several times.

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