运行文件夹中的每个文件



我可以写一个R脚本来打开并运行文件夹中的每个R文件吗?

我知道如何检查文件夹中是否存在文件,如何将文件夹中的每个文件作为文本连接读取,以及如何读取文件夹中的每一个数据文件。

但是,我希望一次执行文件夹中的每个R脚本,最好使用单个R脚本和安装期间安装在Windows桌面上的默认R gui。

我怀疑我可能需要从命令行运行R,并编写某种批处理文件来执行此操作。我很少从命令行运行R,也从未为R编写过批处理文件。

以下是一些示例R脚本,它们都存储在名为run_all_these:的文件夹中

文件run.one.r包含:

a <- 10
b <- 20
c <- a+b
c

文件run.two.r包含:

a <- 10
b <- 20
c <- a-b
c

文件run.three.r包含:

a <- 10
b <- 20
c <- a*b
c

文件run.four.r包含:

a <- 10
b <- 20
c <- a/b
c

我在谷歌上几乎找不到任何关于这个话题的内容。尽管如此,我确实在这里找到了一些关于批处理文件的信息:

http://cran.r-project.org/bin/windows/base/rw-FAQ.html

当运行时,我的实际R脚本将各自创建自己的输出文件。所以,我现在最关心的是运行R脚本。尽管下一步是打开每个R脚本,但将a10更改为100,然后再次运行它们。也许这应该是一个后续帖子。

谢谢你的建议。

编辑2013年11月20日:

在下面与Ricardo Saporta讨论后,我将四个输入文件更改为:

文件run.one.r:

a <- 10
b <- 20
c <- a+b
print(c)

文件run.two.r:

a <- 10
b <- 20
c <- a-b
print(c)

文件run.three.r:

a <- 10
b <- 20
c <- a*b
print(c)

文件run.four.r:

a <- 10
b <- 20
c <- a/b
print(c)

我的utils文件中有以下函数:

## finds all .R files within a folder and soruces them
sourceEntireFolder <- function(folderName, verbose=FALSE, showWarnings=TRUE) { 
  files <- list.files(folderName, full.names=TRUE)
  # Grab only R files
  files <- files[ grepl("\.[rR]$", files) ]
  if (!length(files) && showWarnings)
    warning("No R files in ", folderName)
  for (f in files) {
    if (verbose)
      cat("sourcing: ", f, "n")
    ## TODO:  add caught whether error or not and return that
    try(source(f, local=FALSE, echo=FALSE), silent=!verbose)
  }
  return(invisible(NULL))
}
sapply( list.files(run_all_these, full.names=TRUE), source )

您需要确保run_all_these是有效的Windows目录规范。

如果没有子文件夹:

library(tidyverse)
list.files("name_folder", full.names = TRUE) %>% walk(source)

最新更新