rak*_*nsi 37
这对我有用:
getSrcDirectory(function(x) {x})
Run Code Online (Sandbox Code Playgroud)
这在脚本中定义了一个匿名函数(什么都不做),然后确定该函数的源目录,即脚本所在的目录.
Ric*_*ton 29
仅适用于RStudio:
setwd(dirname(rstudioapi::getActiveDocumentContext()$path))
Run Code Online (Sandbox Code Playgroud)
这在运行或源文件时有效.
had*_*ley 25
使用 source("yourfile.R", chdir = T)
利用Rscript的隐式"--file"参数
使用"Rscript"(Rscript doc)调用脚本时,脚本的完整路径将作为系统参数给出.以下函数利用此功能提取脚本目录:
getScriptPath <- function(){
cmd.args <- commandArgs()
m <- regexpr("(?<=^--file=).+", cmd.args, perl=TRUE)
script.dir <- dirname(regmatches(cmd.args, m))
if(length(script.dir) == 0) stop("can't determine script dir: please call the script with Rscript")
if(length(script.dir) > 1) stop("can't determine script dir: more than one '--file' argument detected")
return(script.dir)
}
Run Code Online (Sandbox Code Playgroud)
如果将代码包装在包中,则始终可以查询包目录的一部分。
这是RGtk2软件包的示例:
> system.file("ui", "demo.ui", package="RGtk2")
[1] "C:/opt/R/library/RGtk2/ui/demo.ui"
>
Run Code Online (Sandbox Code Playgroud)
您可以对inst/glade/
源代码中的目录执行相同操作,该目录将成为glade/
已安装软件包中的目录-并system.file()
在安装时为您计算路径,而与操作系统无关。
归档时间: |
|
查看次数: |
45872 次 |
最近记录: |