简体   繁体   English

如何从系数列表中获取lm对象并在R中截取

[英]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.我有一个带有截距的系数列表,我想从中创建一个 R lm 对象。 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.如果我们知道截距和斜率并且 x 是我们想知道 y 的某个值,我们可以使用 y = 截距 + 斜率 * x。 (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.上面很简单,我们实际上并不需要一个lm对象来做它,但是如果你真的想要一个lm对象,那么因为一条线是由两个点确定的,我们可以使用这两个,它们遵循上面的等式。

  • x = 0, y = intercept x = 0, y = 截距
  • x = 1, y = intercept + slope x = 1, y = 截距 + 斜率

so using those fm below is the required lm object.所以使用下面的那些fm是所需的lm对象。 (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.) (如果我们有多个预测变量,则考虑它们全为 0 的点以及其中一个为 1 而其余为 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.已经更新好几次了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM