首页 > 解决方案 > setwd() 来自 R 中的批处理文件

问题描述

我想从批处理文件运行 R 脚本以自动化相同的过程,并希望在批处理文件中设置工作目录。

R 脚本

files <- list.files(pattern=*.csv", full.names=TRUE, 
recursive=FALSE)

lapply(files, function(x) {

  df <- read.csv(x, header = TRUE, sep = ",")

 inds <- which(df$pc_no == "DELL")
 df[inds - 1, c("event_rep", "loc_id")] <- df[inds, c("pc_no", "cust_id")]
 df1 <- df[-inds, ]

 write.csv(df1, paste0('cleaned_', x), row.names = FALSE)

}

批处理文件

"C:\R\R-3.5.1\bin\i386\R.exe" CMD BATCH 
"C:\folder\myscript.R" -e setwd("C:\Documents") 
"C:\folder\test.Rout"

我怎样才能做到这一点?

标签: rbatch-filecommand-lineautomation

解决方案


您可以使用commandArgs()withRscript轻松获得所需的行为。考虑以下我调用的 R 脚本so-answer.R

# First get the argument giving the desired working directory:
wd <- commandArgs(trailingOnly = TRUE)
# Then check if we can correctly set the working directory:
setwd(wd)
getwd()

然后我们可以从命令行运行它,将我们想要的目录作为参数传递:

duckmayr@duckmayr-laptop:~$ Rscript so-answer.R Documents
[1] "/home/duckmayr/Documents"

commandArgs()可以在此博客文章中找到一个很好的、易于理解的解释。

如果您真的不喜欢使用R CMD BATCH,请查看此博客文章并尝试以下操作:

# First get the argument giving the desired working directory:
eval(parse(text = commandArgs(trailingOnly = TRUE)[1]))
# Then check if we can correctly set the working directory:
setwd(wd)
getwd()

你可以从命令行运行

duckmayr@duckmayr-laptop:~$ R CMD BATCH '--args wd="Documents"' so-answer.R so-answer.Rout

这导致了这个输出

duckmayr@duckmayr-laptop:~$ cat so-answer.Rout

R version 3.5.1 (2018-07-02) -- "Feather Spray"
Copyright (C) 2018 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

  Natural language support but running in an English locale

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

> # First get the argument giving the desired working directory:
> eval(parse(text = commandArgs(trailingOnly = TRUE)[1]))
> # Then check if we can correctly set the working directory:
> setwd(wd)
> getwd()
[1] "/home/duckmayr/Documents"
> 
> proc.time()
   user  system elapsed 
  0.478   0.052   0.495 

推荐阅读