2015-12-13 72 views
1

我想知道將多個迴歸係數輸出到.csv的最佳方式是什麼。R:從多個迴歸輸出到.csv或.xls的輸出係數

我發現了下面的函數,它正是我想要的,但一次只能進行一次迴歸。

lmOut <- function(res, file="test.csv", ndigit=3, writecsv=T) { 
    # If summary has not been run on the model then run summary 
    if (length(grep("summary", class(res)))==0) res <- summary(res) 

    co <- res$coefficients 
    nvar <- nrow(co) 
    ncol <- ncol(co) 
    f <- res$fstatistic 
    formatter <- function(x) format(round(x,ndigit),nsmall=ndigit) 

    # This sets the number of rows before we start recording the coefficients 
    nstats <- 4 

    # G matrix stores data for output 
    G <- matrix("", nrow=nvar+nstats, ncol=ncol+1) 

    G[1,1] <- toString(res$call) 

    # Save rownames and colnames 
    G[(nstats+1):(nvar+nstats),1] <- rownames(co) 
    G[nstats, 2:(ncol+1)] <- colnames(co) 

    # Save Coefficients 
    G[(nstats+1):(nvar+nstats), 2:(ncol+1)] <- formatter(co) 

    # Save F-stat 
    G[1,2] <- paste0("F(",f[2],",",f[3],")") 
    G[2,2] <- formatter(f[1]) 

    # Save F-p value 
    G[1,3] <- "Prob > P" 
    G[2,3] <- formatter(1-pf(f[1],f[2],f[3])) 

    # Save R2 
    G[1,4] <- "R-Squared" 
    G[2,4] <- formatter(res$r.squared) 

    # Save Adj-R2 
    G[1,5] <- "Adj-R2" 
    G[2,5] <- formatter(res$adj.r.squared) 

    print(G) 
    if (writecsv) write.csv(G, file=file, row.names=F) 
} 

我的想法是使用一個for循環運行此迴歸20次,然後想出一個辦法,以20層的.csv的結合到Excel電子表格包含多個選項卡。

我有二十個迴歸,像r_1,r_2,..,r_20一樣。

我是新來R.我想是這樣的

for(i in 1:20) 
{ 

    name<- paste("r_", i, sep = "") 
    csvname<- paste("r_", i, ".csv", sep= "") 
    lmOut(name, file= csvname) 
} 

但是,這是行不通的。有任何想法嗎?

回答

2

爲什麼不去做這樣的:

library(broom) 
r_1 <- r_2 <- r_20 <- lm(weight ~ group, PlantGrowth) 
lst <- mget(grep("^r_\\d+$", ls(), value = TRUE)) 
write.csv2(do.call(rbind, lapply(lst, tidy)), tf <- tempfile(fileext = ".csv")) 
file.show(tf) 
#    term estimate std.error statistic  p.value 
# r_1.1 (Intercept) 5.032 0.1971284 25.526514 1.936575e-20 
# r_1.2 grouptrt1 -0.371 0.2787816 -1.330791 1.943879e-01 
# r_1.3 grouptrt2 0.494 0.2787816 1.771996 8.768168e-02 
# r_2.1 (Intercept) 5.032 0.1971284 25.526514 1.936575e-20 
# r_2.2 grouptrt1 -0.371 0.2787816 -1.330791 1.943879e-01 
# r_2.3 grouptrt2 0.494 0.2787816 1.771996 8.768168e-02 
# r_20.1 (Intercept) 5.032 0.1971284 25.526514 1.936575e-20 
# r_20.2 grouptrt1 -0.371 0.2787816 -1.330791 1.943879e-01 
# r_20.3 grouptrt2 0.494 0.2787816 1.771996 8.768168e-02 
+0

這是夢幻般的。謝謝 – Parseltongue