【问题标题】:Get variable names from an lm object without segregating factor levels从 lm 对象中获取变量名而不分离因子级别
【发布时间】:2020-02-04 18:53:33
【问题描述】:

我需要从lm 模型中取回变量名称。 variable.names() 很好,除非其中一个变量是 factor,在这种情况下:

model <- lm(Petal.Length~Petal.Width+Species, data=iris)
variable.names(model)

返回:

"(Intercept)"       "Petal.Width"       "Speciesversicolor"        "Speciesvirginica" 

我需要Speciesvariable 只出现一次,而无需为每个因素指定不同的级别,例如:

"(Intercept)"       "Petal.Width"       "Species" 

【问题讨论】:

  • 你可以做 model$terms[[3]]

标签: r linear-regression


【解决方案1】:

您可以从call 中提取带有all.vars 的名称,删除作为数据的最后一个字符串。

all.vars(model$call)[1:length(model$call)]
# [1] "Petal.Length" "Petal.Width"  "Species"  

【讨论】:

    【解决方案2】:

    获取模型的model.framenames

    names(model.frame(model))
    ## [1] "Petal.Length" "Petal.Width"  "Species"   
    

    或使用terms

    all.vars(terms(model))
    ## [1] "Petal.Length" "Petal.Width"  "Species" 
    

    【讨论】:

      猜你喜欢
      • 2015-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-21
      • 1970-01-01
      • 2014-11-05
      • 1970-01-01
      相关资源
      最近更新 更多