首页 > 解决方案 > 如何在 R 中编写函数来自动选择重要特征?

问题描述

如何编写一个函数来自动化这些过程:

  1. 针对 0.05 阈值选择重要特征
  2. 选择三个最重要的功能

到目前为止,我的就是这个,但它不起作用。我可以列出功能,但不能编写一个功能来做这两个!

lm.fit <- glm(formula = Salary ~., data=train, family = binomial)
glm.coef.sig <- data.frame(summary(glm.fit)$coef[summary(glm.fit)$coef[,4] < .05, 4])
glm.coef.sig

标签: r

解决方案


这是一个示例工作流程:

features <- "."
repeat{
  lm(formula=paste0("wt ~ ", paste0(features, collapse="+")), mtcars) -> lm.fit
  # get the coefficients that are significant
  summary(lm.fit)$coef[-1, 4] <.05 -> summ
  # check if the selected features are the features we already had if so break
  # if not change feature to selected features
  if(identical(features, names(summ)[summ])){
    break
  } else features = names(summ)[summ]
}

推荐阅读