为目录中的多个文件循环线性模型

时间:2016-10-25 12:36:26

标签: r loops regression linear-regression lm

我有一个包含26个.csv文件的文件夹。每个文件都有两列,标题为DO2Time_min,所有行至少有300多行。

我想制作一个包含x=Time_miny=DO2的散点图,为每个模型制作线性模型,为26个模型中的每个模型取coefficientR^2并将其放入一张桌子。

就代码而言,这就是我所写的内容。我知道我可以复制并粘贴它,但我也知道必须有一个更聪明的方法。

setwd("~/Documents/Masters/Data/R/35789/35789_Ucrit")

#The file where I want all the coefficients and R^2 to go
UE_Slope <- read.csv("~/Documents/Masters/Data/R/35789/35789_UE_Slope.csv")

temp = list.files(pattern="*.csv")
for (i in 1:length(temp))(assign(temp[i], read.csv(temp[i])))

#Seal# are the names for the files directory, 1-26
plot(DO2 ~ Time_min, data = Seal1)
model1 <- lm(DO2 ~ Time_min, data = Seal1.csv)
UE_Slope <- rbind(UE_Slope, data.frame("Slope"=coef(model1)[[2]], "R.2"=summary(model1)$r.squared))

1 个答案:

答案 0 :(得分:2)

我们首先定义一个函数,它读取“csv”文件,适合线性模型并获得汇总统计信息。

f <- function (file) {
  ## read file
  dat <- read.csv(file)
  ## fit model
  fit <- lm(DO2 ~ Time_min, data = dat)
  slope <- coef(fit)[2]
  ## make a plot??
  plot(DO2 ~ Time_min, data = dat, main = file)  ## use file names as title
  abline(fit)  ## overlay fitted regression line
  ## note, I am not using `summary.lm` as that is expensive
  ## R-squared can be easily computed
  RSS <- crossprod(fit$residuals)[1]
  TSS <- crossprod(dat$DO2 - mean(dat$DO2))[1]
  R2 <- 1 - RSS / TSS
  ## return a vector
  c("Slope" = slope, "R.2" = R2)
  }

现在,我们只需遍历所有文件,应用f

temp <- list.files(pattern = "*.csv")
pdf("whatever.pdf")
result <- t(sapply(temp, f))
dev.off()

sapplycbind最终得到一个平面矩阵;使用t()使其成为一个高大的矩阵。 pdf()dev,off()打开/关闭PDF文件,并在该文件上生成所有图表。这看起来很有必要,因为你有26个数字,不容易在屏幕上以面板方式显示它们。通过使用PDF文件,每页可以有一个图。 PDF文件将在您当前的工作目录中。