filename = "your_file.R"
filepath = file.choose() # browse and select your_file.R in the window
dir = substr(filepath, 1, nchar(filepath)-nchar(filename))
setwd(dir)
# SET WORKING DIRECTORY TO CURRENT DIRECTORY:
system("pwd=`pwd`; $pwd 2> dummyfile.txt")
dir <- fread("dummyfile.txt")
n<- colnames(dir)[2]
n2 <- substr(n, 1, nchar(n)-1)
setwd(n2)
这有点复杂,但基本上是使用系统命令获取工作目录并保存到 Dummyfile.txt,然后 R 使用 data.table: : fread 读取该文件。其余部分只是清理打印到文件中的内容,这样就只剩下目录路径了。
library(rstudioapi)
# Getting the path of your current open file
current_path = rstudioapi::getActiveDocumentContext()$path
setwd(dirname(current_path ))
print( getwd() )