Search code examples
rlinear-regressionlm

How do I grab the variable names that are non-NA in a linear model?


library(datasets)
data(iris)
summary(iris)

iris$married = c(0)
iris$death = c(0)
iris$test = c(0)

regressor = lm(Sepal.Length ~ ., data = iris)
summary(regressor)

string = coef(summary(regressor))[2:summary(regressor)$fstatistic[2]+1,0]
string

names = c("Petal.Length","Petal.Width","Speciesversicolor","Speciesvirginica")

enter image description here

I can get it to output the non-na coefficients but I want to turn it into a list of characters like in 'names'. When I store it in 'string' it just becomes a weird num[1:4,0] type.


Solution

  • You can use this code to extract the names of the coefficients from the summary:

    library(datasets)
    data(iris)
    summary(iris)
    
    iris$married = c(0)
    iris$death = c(0)
    iris$test = c(0)
    
    regressor = lm(Sepal.Length ~ ., data = iris)
    summary <- summary(regressor)
    
    string = row.names(summary$coefficients)[c(-1)]
    string
    

    Output string:

    [1] "Sepal.Width"       "Petal.Length"      "Petal.Width"       "Speciesversicolor" "Speciesvirginica"