我想知道将多个回归系数输出到.csv的最佳方法是什么。
我找到了以下功能,它完全符合我的要求,但一次只能进行一次回归。
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)
}
但这不起作用。有什么想法吗?
答案 0 :(得分: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