PDiddyA
PDiddyA

Reputation: 59

Is it possible to extract the names of coefficients from $terms?

I have a test linear model:

set.seed(93874)
test_x <- rnorm(1000)
test_y <- rnorm(1000) + test_x
model  <- lm(test_y ~ test_x)

with the coefficients "intercept" and "test_x":

model$coefficients
(Intercept)      test_x 
 0.04047742  0.98198305 

Using the command model$terms gives quite a bit of data

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

from which I feel that I should be able to pull the names of the coefficients and use as row names in a matrix similar to the one generated by

 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

Is there a way to do this with a package or a command/function? I do not want to explicitly name the rows as doing so will make adding and removing variables in my actual program extremely cumbersome.

Upvotes: 0

Views: 422

Answers (1)

dhc
dhc

Reputation: 787

You can use

names(model$coefficients)
[1] "(Intercept)" "test_x" 

Or equivalently

> names(coef(model))
[1] "(Intercept)" "test_x" 

Upvotes: 3

Related Questions