将stepAIC的结果写入表中

时间:2014-11-24 21:21:22

标签: r

我正在尝试将stepAIC中的r2,rmse,系数和标准化系数写入.CSV文件:

NO3_lmres_ClimateOnly <- data.frame()
for (i in unique(Data$SeasAlltxt)){
  print (i)
  subdata1 <- subset(Data, SeasAlltxt == i)
  for (j in unique(Data$ALSCIDtxtall)){
    subdata2 <- subset(subdata1, ALSCIDtxtall == j)
    fit <- lm(NO3resid~Avg94NO3+MaxDepth_m+MaxDepthDOY+FirstZeroDOY+PeakToGone+PRISMppt+PRISMtmax, data = subdata2, na.action = na.omit)
    step <- stepAIC(fit, direction="both")

    rmse <- round(sqrt(mean(resid(step)^2)), 3)
    r2 <- round(summary(step)$r.squared, 3)
    coefs <- summary(step)$coefficients
    stdcoefs <- lm.beta(step)
    stdcoefs <- unname(stdcoefs)
    params <- names(stdcoefs)

    tempvalues <- data.frame(i,j,rmse,r2,coefs,stdcoefs,params)
    colnames(tempvalues) <- c('SeasAlltxt', 'ALSCIDtxtall', 'rmse', 'r2', 'coef', 'stdcoef','param')
    NO3_lmres_ClimateOnly <- rbind(NO3_lmres_ClimateOnly,tempvalues)
  }
}

write.csv(NO3_lmres_ClimateOnly, file = "NO3_ClimateOnly_stats.csv")

但是,上面的代码会产生此错误:

Error in data.frame(i, j, rmse, r2, coefs, stdcoefs, params) : 
  arguments imply differing number of rows: 1, 3, 2, 0

我还想将与每个参数关联的p值写入输出表。

有关如何完成此任务的任何建议?

1 个答案:

答案 0 :(得分:0)

也许您想要更改代码:

for (j in unique(subdata1$ALSCIDtxtall))

...

 coefs <- summary(step)$coefficients[,1]

...

tempvalues  <- data.frame(t(c(i,j,rmse,r2,coefs,stdcoefs,params)),stringsAsFactors=F)
colnames(tempvalues ) <- c('SeasAlltxt', 'ALSCIDtxtall', 'rmse', 'r2', names(coefs), paste('stdcoef:',params),params)

stepAIC 选择不同数量的系数时,最后一个rbind会给你一个错误。

考虑使用列表:

之外定义cont=1 然后,更改以下行:

tempvalues  <- data.frame(t(c(i,j,rmse,r2,coefs,stdcoefs,params)),stringsAsFactors=F)
    colnames(tempvalues ) <- c('SeasAlltxt', 'ALSCIDtxtall', 'rmse', 'r2', names(coefs), paste('stdcoef:',params),params)
    NO3_lmres_ClimateOnly[[cont]] <- tempvalues
    cont=cont+1
祝你好运!!