我有一个测试线性模型:
set.seed(93874)
test_x <- rnorm(1000)
test_y <- rnorm(1000) + test_x
model <- lm(test_y ~ test_x)
带有系数"intercept"one_answers"test_x"
model$coefficients
(Intercept) test_x
0.04047742 0.98198305
使用命令model$terms
提供了相当多的数据
> model$terms
test_y ~ test_x
attr(,"variables")
list(test_y, test_x)
attr(,"factors")
test_x
test_y 0
test_x 1
attr(,"term.labels")
[1] "test_x"
attr(,"order")
[1] 1
attr(,"intercept")
[1] 1
attr(,"response")
[1] 1
attr(,".Environment")
<environment: R_GlobalEnv>
attr(,"predvars")
list(test_y, test_x)
attr(,"dataClasses")
test_y test_x
"numeric" "numeric"
,我觉得我应该能够从中提取系数的名称,并将其用作矩阵中的行名,类似于
生成的矩阵。rows <- c("test_x")
cols <- c("Value")
matrix_test <- matrix(c(1), nrow = 1, ncol = 1, byrow = TRUE, dimnames = list(rows, cols))
> matrix_test
Value
test_x 1
是否有一种方法可以用包或命令/函数来做到这一点?我不想显式地命名行,因为这样做会使在实际程序中添加和删除变量变得非常麻烦。
可以使用
names(model$coefficients)
[1] "(Intercept)" "test_x"
或者
> names(coef(model))
[1] "(Intercept)" "test_x"