相关疑难解决方法(0)

获取当前脚本的路径

我想以编程方式将工作目录设置为当前脚本的路径,但首先我需要获取当前脚本的路径.

所以我希望能够做到:

current_path = ...retrieve the path of current script ...
setwd(current_path) 
Run Code Online (Sandbox Code Playgroud)

就像RStudio菜单一样: RStudio设置工作目录

到目前为止我试过:

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)
Run Code Online (Sandbox Code Playgroud)

script.name 返回NULL

source("script.R", chdir = TRUE)
Run Code Online (Sandbox Code Playgroud)

返回:文件中的错误(文件名,"r",编码=编码):无法打开连接另外:警告消息:在文件中(文件名,"r",编码=编码):无法打开文件'/script.R' : 没有相应的文件和目录

dirname(parent.frame(2)$ofile)
Run Code Online (Sandbox Code Playgroud)

返回:dirname中的错误(parent.frame(2)$ ofile):期望的字符向量参数 ...因为parent.frame为null

frame_files <- lapply(sys.frames(), function(x) x$ofile)
frame_files <- Filter(Negate(is.null), frame_files)
PATH <- dirname(frame_files[[length(frame_files)]])
Run Code Online (Sandbox Code Playgroud)

返回:Null,因为frame_files是0的列表

thisFile <- function() {
    cmdArgs <- commandArgs(trailingOnly = FALSE)
    needle <- "--file="
    match <- grep(needle, cmdArgs)
    if (length(match) > 0) …
Run Code Online (Sandbox Code Playgroud)

r rstudio

25
推荐指数
6
解决办法
3万
查看次数

标签 统计

r ×1

rstudio ×1