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

Looping linear models for multiple files in directory

我有一个包含 26 个 .csv 文件的文件夹。每个文件都有两列 headers DO2Time_min 并且都至少有 300 多行。

我想用 x=Time_miny=DO2 制作散点图,为每个模型制作线性模型,为 26 个模型中的每一个取 coefficientR^2 并放入它在 table.

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

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))

我们首先定义一个函数,读取"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()

sapply do cbind 以平面矩阵结束;使用 t() 使其成为高矩阵。 pdf()dev,off() 打开/关闭 PDF 文件,所有绘图都在该文件上进行。这看起来很有必要,因为您有 26 个数字,不容易在屏幕上以面板方式显示它们。通过使用 PDF 文件,您可以每页绘制一个图。 PDF 文件将位于您当前的工作目录中。