【发布时间】:2018-04-13 03:12:35
【问题描述】:
我想以编程方式将工作目录设置为当前脚本的路径,但首先我需要获取当前脚本的路径。
所以我希望能够做到:
current_path = ...retrieve the path of current script ...
setwd(current_path)
到目前为止我尝试过:
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)
script.name 返回 NULL
source("script.R", chdir = TRUE)
返回: 文件错误(文件名,“r”,编码 = 编码):无法打开 连接另外:警告消息:在文件中(文件名,“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' 参数无效
我还看到了来自here、here、here 和here 的所有答案。 不开心。
使用RStudio 1.1.383
编辑:如果不需要外部库来实现这一点,那就太好了。
【问题讨论】:
-
source("<path to file>/script.R", chdir = TRUE)可能会像帮助文件中所说的 chdir 一样起作用:* 如果 TRUE 且文件是路径名,则 R 工作目录临时更改为包含用于评估的文件的目录。* 错误消息你会说 R 在当前工作目录中找不到名为 script.R 的文件。 -
我的文件名是 lpp.R,我确实给了这个名字......我记得在其他版本的 RStudio 中我很容易用父框架做到了,现在什么都没有
-
在 R studio 项目文件夹中,最好假设所有文件路径都相对于项目的根目录。见Stop the working directory insanity。我个人不使用它,但建议使用 here 包来查找给定文件的位置。
-
@Imo -- 仅当您获取文件时才有效,但如果您使用 Rscript 调用它则无效。
-
@PaulRougieux -- 仅当您正在运行(或采购)的文件位于项目目录中时才有效。如果您在其他位置运行(或获取)文件,它将无法正常工作。