考虑下面的两个data.frames
。在每种情况下,我想从相关模型中提取截距,并对三个变量进行斜率。
set.seed(911)
df1 <- data.frame(y=rnorm(10) + 1:10, x=1:10, x2=rnorm(10), x3 = rnorm(10))
model1 <- lm(y ~ x + x2 + x3, data = df1)
summary(model1)
summary(model1)$coefficients[1]
summary(model1)$coefficients[2]
summary(model1)$coefficients[3]
summary(model1)$coefficients[4]
set.seed(911)
df2 <- data.frame(y=rnorm(10) + 1:10, x=1:10, x2=1, x3 = rnorm(10))
model2 <- lm(y ~ x + x2 + x3, data = df2)
summary(model2)
summary(model2)$coefficients[1]
summary(model2)$coefficients[2]
summary(model2)$coefficients[3]
summary(model2)$coefficients[4]
但是,在第二个示例中,x2
没有变化,因此系数估计值为NA
。重要的是,summary(model2)
会打印NA
,但summary(model2)$coefficients[3]
不会返回NA
,但会跳过并移至下一个参数。
但我想要:
0.9309032
0.8736204
NA
0.5494
如果我在adnavce中不知道哪些系数为NA
,即它可能是x1
,x2
或x2 &
x3 or even something like
x1 {{ 1}} x2 &
x3`,如何返回我想要的结果?
答案 0 :(得分:2)
直接从模型中抓取它们。无需使用summary()
:
> model2$coefficients
(Intercept) x x2 x3
0.9309032 0.8736204 NA 0.5493671