#' current script dir
#' @param
#' @return
#' @examples
#' works with source() or in RStudio Run selection
#' @export
z.csd <- function() {
# http://stackoverflow.com/questions/1815606/rscript-determine-path-of-the-executing-script
# must work with source()
if (!is.null(res <- .thisfile_source())) res
else if (!is.null(res <- .thisfile_rscript())) dirname(res)
# http://stackoverflow.com/a/35842176/2292993
# RStudio only, can work without source()
else dirname(rstudioapi::getActiveDocumentContext()$path)
}
# Helper functions
.thisfile_source <- function() {
for (i in -(1:sys.nframe())) {
if (identical(sys.function(i), base::source))
return (normalizePath(sys.frame(i)$ofile))
}
NULL
}
.thisfile_rscript <- function() {
cmdArgs <- commandArgs(trailingOnly = FALSE)
cmdArgsTrailing <- commandArgs(trailingOnly = TRUE)
cmdArgs <- cmdArgs[seq.int(from=1, length.out=length(cmdArgs) - length(cmdArgsTrailing))]
res <- gsub("^(?:--file=(.*)|.*)$", "\\1", cmdArgs)
# If multiple --file arguments are given, R uses the last one
res <- tail(res[res != ""], 1)
if (length(res) > 0)
return (res)
NULL
}
8 回答
这个答案对我很好:
注意:必须获取脚本才能返回正确的路径
我找到了:https://support.rstudio.com/hc/communities/public/questions/200895567-can-user-obtain-the-path-of-current-Project-s-directory-
但我仍然不明白什么是sys.frame(1)$ ofile . 我在R文档中没有找到任何相关内容 . 有人可以解释一下吗?
如何使用系统和shell命令?使用windows one,我认为当你在RStudio中打开脚本时,它会将当前的shell目录设置为脚本目录 . 您可能必须添加cd C:\例如或您要搜索的任何驱动器(例如shell('dir C:\ * file_name / s',intern = TRUE) - \以转义转义字符) . 除非您进一步指定子目录(对于我从/开始搜索的Linux),否则仅适用于唯一命名的文件 . 在任何情况下,如果你知道如何在shell中找到一些东西,这提供了一个布局,可以在R中找到它并返回目录 . 无论您是采购还是运行脚本,都应该工作,但我还没有充分发现潜在的错误 .
这对我有用:
这在脚本中定义了一个匿名函数(什么都不做),然后确定该函数的源目录,即脚本所在的目录 .
仅适用于RStudio:
这在运行或源文件时有效 .
使用
source("yourfile.R", chdir = T)
如果将代码包装在包中,则始终可以查询包目录的某些部分 .
以下是RGtk2包中的示例:
您可以对源中的目录
inst/glade/
执行相同操作,该目录将成为已安装软件包中的目录glade/
- 并且system.file()
将在安装时为您计算路径,而与操作系统无关 .Exploit the implicit "--file" argument of Rscript
使用"Rscript"(Rscript doc)调用脚本时,脚本的完整路径将作为系统参数给出 . 以下函数利用此功能提取脚本目录: