J4y*_*J4y 6 shell command-line r
我有一个脚本(调用它Main.R),它具有以下代码,以便在运行时找到它自己:
frame_files <- lapply(sys.frames(), function(x) x$ofile)
frame_files <- Filter(Negate(is.null), frame_files)
main.dir <- dirname(dirname(frame_files[[length(frame_files)]]))
Run Code Online (Sandbox Code Playgroud)
这用于获取其自己的目录上方的目录main.dir,该目录用于调用与此路径相关的其他脚本.
例如,我对从命令行运行此脚本感兴趣
R CMD BATCH Main.R
Run Code Online (Sandbox Code Playgroud)
要么
Rscript Main.R
Run Code Online (Sandbox Code Playgroud)
不幸的是,当我从命令行调用脚本时,上面的命令不起作用.
我可以输入任何代码或者我可以使用Main.R的呼叫选项吗?RRscript
更具体地说,该解决方案需要在Windows中运行.
下面是一个解决方案,当使用source或使用Rscript 运行脚本时,它将为您提供正确的文件目录路径.
# this is wrapped in a tryCatch. The first expression works when source executes, the
# second expression works when R CMD does it.
full.fpath <- tryCatch(normalizePath(parent.frame(2)$ofile), # works when using source
error=function(e) # works when using R CMD
normalizePath(unlist(strsplit(commandArgs()[grep('^--file=', commandArgs())], '='))[2]))
dirname(full.fpath)
Run Code Online (Sandbox Code Playgroud)
关键是功能normalizePath.给定相对或缩写的路径名称,normalizePath将返回有效路径或引发错误.从Rscript运行脚本时,如果给出normalizePath当前脚本的基本文件名,它将返回完整路径,无论您当前的目录是什么.当你提供R CMD的相对路径并且当前目录中有一个同名的脚本时,它甚至可以获得正确的路径!
在上面的代码中,我从返回的其中一个字符串中提取文件名commandArgs.如果你看看输出commandArgs,你会看到文件名是第四个参数.参数记录为'--file = yourscript.R',因此在上面的最后一行中,我将字符串拆分为'='并拉出文件名.
| 归档时间: |
|
| 查看次数: |
1431 次 |
| 最近记录: |