I would like to set the working directory to the path of the current script programmatically, but first I need to get the path to the current script.
So, I would like to be able to do:
current_path = ...retrieve the path of current script ... setwd(current_path)
Same as in the RStudio menu: 
So far I have tried:
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 returns NULL
source("script.R", chdir = TRUE)
Returns : Error in the file (file name, "r", encoding = encoding): cannot open the connection. Additional: Warning message: In the file (file name, "r", encoding = encoding): cannot open the file '/ script.R ': no such file or directory
dirname(parent.frame(2)$ofile)
Returns : error in dirname (parent.frame (2) $ ofile): expected character symbol argument ... because parent.frame is 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)]])
Returns : Zero because frame_files is a list of 0
thisFile <- function() { cmdArgs <- commandArgs(trailingOnly = FALSE) needle <- "--file=" match <- grep(needle, cmdArgs) if (length(match) > 0) {
Returns : error in path .expand (path): invalid path argument
I also saw all the answers here , here , here and here . There is no joy.
Work with RStudio 1.1.383
EDIT: It would be great if you did not need an external library for this.