r - 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"
我怎样才能做到这一点?
解决方案
您可以使用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
推荐阅读
- python - 为什么玩家落地时平台的速度会发生变化?
- angularjs - 在angularjs中获取“无法读取未定义的属性'缩略图'”
- assembly - 将水平和垂直线绘制到 VBE 返回的 LFB 的结果不正确
- algorithm - 如果 m <= n,时间复杂度 O(nm) 是否等于 O(n^2)
- java - Kotlin + Java 9 模块(使用 Java 11)+ maven
- c# - 在运行时添加 ASP.Net 按钮事件处理程序不起作用
- flutter - 我在 Flutter 应用程序中升级软件包时遇到了一些问题
- python - 我如何通过在 Pandas 数据框中具有相同的值来“合并”行分组?
- linux - Linux 命令行 - 列出所有包含 .js 文件的目录,并将目录及其内容复制到新文件夹中
- ios - 如何在 SwiftUI 中更改每个视图的状态栏文本颜色?