如何获取线性模型中非 NA 的变量名?

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

我可以让它输出非 na 系数,但我想把它变成像 'names' 中那样的字符列表。当我将它存储在 'string' 中时,它就变成了一个奇怪的 num[1:4,0] 类型。

您可以使用此代码从摘要中提取系数的名称:

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

输出字符串:

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