【问题标题】:Print and export loop from simple linear regression从简单的线性回归打印和导出循环
【发布时间】:2021-07-13 03:17:34
【问题描述】:

我做了一个循环来在数据集中执行许多简单的线性回归。但是,我只想打印满足特定阈值的结果(即:R-squared > 30% 和 p-value

predictorlist = colnames(finalmev)[-1]
sink('mev.txt')
for (i in predictorlist){ 
  model <- summary(lm(paste("ODR ~", i[[1]]), data=finalmev))
  if (model$r.squared > 0.30 && model$coefficients[2,4] < 0.05){
    print(data.frame(MEV = i[[1]], Rsquared = model$r.squared,
                     pvalue = model$coefficients[2,4]))
    sink()
  }
}

【问题讨论】:

    标签: r loops linear-regression export-to-excel


    【解决方案1】:

    以lapply为例,以mtcars为例-

    predictorlist = colnames(mtcars)[-1]
    
    do.call(rbind, lapply(predictorlist, function(x) {
      model <- summary(lm(paste("mpg ~", x), data=mtcars))
      rsq = model$r.squared
      pval = model$coefficients[2,4]
      if (rsq > 0.30 && pval < 0.05) 
         data.frame(MEV = x, Rsquared = rsq, pvalue = pval)
    })) -> res
    
    
    write.csv(res, 'mev.csv', row.names = FALSE)
    #If you want to write it as text file
    #write.table(res, 'mev.txt')
    

    【讨论】:

    • 太棒了!正是我需要的。非常感谢
    猜你喜欢
    • 2021-09-14
    • 2022-01-12
    • 1970-01-01
    • 2016-01-17
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 2021-07-02
    • 1970-01-01
    相关资源
    最近更新 更多