【问题标题】:R loop for anova on multiple filesR循环在多个文件上进行方差分析
【发布时间】:2013-01-04 01:12:57
【问题描述】:

我想对存储在我的工作目录中的多个数据集执行anova。到目前为止,我想出了:

files <- list.files(pattern = ".csv")
for (i in seq_along(files)) {
    mydataset.i <- files[i]
    AnovaModel.1 <- aov(DES ~ DOSE, data=mydataset.i)
    summary(AnovaModel.1)
} 

如您所见,我对循环非常陌生,无法完成这项工作。我也知道我需要添加一个代码以将所有摘要输出附加到一个文件中。我将不胜感激您可以提供任何帮助来指导工作循环,该循环可以在目录中的多个 .csv 文件(相同的标题)上执行 anovas 并生成记录输出。

【问题讨论】:

  • 我想捕获所有的输出。我的输出通常看起来像一个典型的方差分析表。

标签: r loops anova


【解决方案1】:

您可能希望将list.filesfull.names = TRUE 一起使用,以防您不在同一条路径上。

files <- list.files("path_to_my_dir", pattern="*.csv", full.names = T)
# use lapply to loop over all files
out <- lapply(1:length(files), function(idx) {
    # read the file
    this.data <- read.csv(files[idx], header = TRUE) # choose TRUE/FALSE accordingly
    aov.mod <- aov(DES ~ DOSE, data = this.data)
    # if you want just the summary as object of summary.aov class
    summary(aov.mod)
    # if you require it as a matrix, comment the previous line and uncomment the one below
    # as.matrix(summary(aov.mod)[[1]])
})
head(out)

这应该给你一个list,列表中的每个条目都有一个summary matrix,与输入文件列表相同的顺序

【讨论】:

  • 谢谢,我可以运行脚本没有任何错误(使用 Rstudio),但我在控制台中看不到输出。
  • 在“head(out)”之前一切都运行良好。我得到:'错误:意外符号:“} head”'
  • 你是对的,代码运行良好。我在控制台窗口中得到了我的 ANOVA 摘要,我只需要努力将它输出到文本文件中。非常感谢。
  • 您好 Arun,我正在尝试通过添加多个模型来修改脚本。例如另一个 aov.mod.1
【解决方案2】:

你的错误是你的循环没有加载你的数据。您的文件名列表在“文件”中,然后您开始浏览该列表并将 mydataset.i 设置为与您的迭代器 i 匹配的文件的名称...但是您尝试在文件名上运行 aov存储在 mydataset.i 中!

您正在寻找将输出重定向到文件的命令是 sink。考虑以下几点:

sink("FileOfResults.txt") #starting the redirect to the file
files <- list.files("path_to_my_dir", pattern="*.csv", full.names = T) #using the fuller code from Arun
for (i in seq_along(files)){
   mydataset.i <- files[i]
   mydataset.d <- read.csv(mydataset.i) #this line is new
   AnovaModel.1 <- aov(DES ~ DOSE, data=mydataset.d) #this line is modified
   print(summary(AnovaModel.1))
} 
sink() #ending the redirect to the file

我更喜欢 Arun 的这种方法,因为结果直接存储到文件中,无需跳过列表,然后必须弄清楚如何以可读的方式将列表存储到文件中。

【讨论】:

  • 谢谢,这看起来很干净,我似乎理解代码背后的想法。我确实在我的工作目录中获得了 FileOfResluts.txt 文件,并且没有其他错误。但是,“FileOfResults.txt”是空白/空的。我是否可能需要使用打印命令来创建输出?
  • 有趣。很有可能...您可能需要用 print 包装您的摘要函数调用。
  • 是的,需要打印,我已修改脚本以反映这一点。
  • 谢谢。这非常有帮助和教育意义。
猜你喜欢
  • 1970-01-01
  • 2015-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-22
  • 2016-02-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多