所以我希望能够做到:
current_path = ...retrieve the path of current script ...
setwd(current_path)
就像RStudio菜单一样: {{link1:}}
到目前为止,我尝试了:
initial.options <- commandArgs(trailingOnly = FALSE)
file.arg.name <- "--file="
script.name <- sub(file.arg.name, "", initial.options[grep(file.arg.name, initial.options)])
script.basename <- dirname(script.name)
返回 NULL。source("script.R", chdir = TRUE)
返回值:文件(filename, "r", encoding = encoding)中出现错误:无法建立连接。此外,警告信息如下:在文件(filename, "r", encoding = encoding)中有一个警告:无法打开文件 '/script.R':没有这样的文件或目录。dirname(parent.frame(2)$ofile)
返回:dirname(parent.frame(2)$ofile)中的错误:预期一个字符向量参数 ...因为parent.frame为空
frame_files <- lapply(sys.frames(), function(x) x$ofile)
frame_files <- Filter(Negate(is.null), frame_files)
PATH <- dirname(frame_files[[length(frame_files)]])
返回:空,因为frame_files是一个长度为0的列表。
thisFile <- function() {
cmdArgs <- commandArgs(trailingOnly = FALSE)
needle <- "--file="
match <- grep(needle, cmdArgs)
if (length(match) > 0) {
# Rscript
return(normalizePath(sub(needle, "", cmdArgs[match])))
} else {
# 'source'd via R console
return(normalizePath(sys.frames()[[1]]$ofile))
}
}
返回:path.expand(path)中的错误:无效的“path”参数
使用RStudio 1.1.383
工作
编辑:如果不需要外部库来实现这一点,那就太好了。
source("<路径>/script.R", chdir = TRUE)
会起作用,因为帮助文件关于 chdir 的说明如下:如果为 TRUE 并且文件是一个路径名,则 R 工作目录会在评估过程中暂时更改为包含文件的目录。 您收到的错误消息表明 R 在当前工作目录中找不到名为 script.R 的文件。 - lmo