Get the path from the current script

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: RStudio install working directory

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) { # Rscript return(normalizePath(sub(needle, "", cmdArgs[match]))) } else { # 'source'd via R console return(normalizePath(sys.frames()[[1]]$ofile)) } } 

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.

+24
r rstudio
source share
6 answers

In RStudio, you can get the path to the file currently displayed in the source pane using

 rstudioapi::getSourceEditorContext()$path 

If you only need a directory, use

 dirname(rstudioapi::getSourceEditorContext()$path) 

If you need the name of the file that was run by source(filename) , this is a little more complicated. You need to look for the srcfile variable somewhere on the stack. How far back depends on how you write things, but it's about 4 steps back: for example,

 fi <- tempfile() writeLines("f()", fi) f <- function() print(sys.frame(-4)$srcfile) source(fi) fi 

should print the same thing on the last two lines.

+46
source share

August 2018 update

TL; DR : the here package helps you create a path from the project root folder, regardless of where the R scripts or Rmd documents are stored in the hiearchy folder.

Here the package remains available on CRAN. The development version has been moved to github.com/r-lib/here . The points mentioned on the sites listed below remain valid.

Previous answer

Read Ode here :

Do you have setwd () in your scripts? Please stop doing this. This makes your script very fragile, programmed exactly at the same time and in one place. As soon as you rename or move directories, it breaks. Or maybe you get a new computer? Or maybe someone else needs to run your code?

[...]

Classical presentation of the problem: awkwardness around the ways to build and / or install the working directory in projects with subdirectories. Especially if you use R Markdown and knitr, which confuse many people with the default behavior "working directory = directory where this file is located." [...]

Install the package here :

 install.packages("here") library(here) here() here("construct","a","path") 

Documentation of the here() function:

Starting from the current working directory during package loading, the directory hierarchy will go up here until a directory is found that satisfies at least one of the following conditions:

  • contains a file matching [.] Rproj $ with content matching ^ Version: in the first line
  • [... other options ...]
  • contains the .git directory

After installation, the root directory does not change during an active session R. Here () then adds the arguments to the root directory.

The development version of the package is available on github .

+10
source share

If you run rscript via command line, etc.

 Rscript /path/to/script.R 

The function below will assign this_file /path/to/script

 library(tidyverse) get_this_file <- function(){ commandArgs() %>% tibble::enframe(name=NULL) %>% tidyr::separate(col=value, into=c("key", "value"), sep="=", fill='right') %>% dplyr::filter(key == "--file") %>% dplyr::pull(value) } this_file <- get_this_file() 
+3
source share

March 2019 update

Based on the answers of Alexis Lucattini and user2554330 so that it works both on the command line and in RStudio. Also resolving the outdated as_tibble message

 library(tidyverse) getCurrentFileLocation <- function() { this_file <- commandArgs() %>% tibble::enframe(name = NULL) %>% tidyr::separate(col=value, into=c("key", "value"), sep="=", fill='right') %>% dplyr::filter(key == "--file") %>% dplyr::pull(value) if (length(this_file)==0) { this_file <- rstudioapi::getSourceEditorContext()$path } return(dirname(this_file)) } 
+2
source share

Another way to get the current script path is funr::get_script_path() and you don't need to run your script using RStudio.

+2
source share

I had problems with all of this because they rely on libraries that I couldn't use (due to packrat) until I installed the working directory (which is why I needed to get the path to start).

So here is an approach that just uses the R base. (EDITED to handle windows \ characters in addition to / in paths)

 args = commandArgs() scriptName = args[substr(args,1,7) == '--file='] if (length(scriptName) == 0) { scriptName <- rstudioapi::getSourceEditorContext()$path } else { scriptName <- substr(scriptName, 8, nchar(scriptName)) } pathName = substr( scriptName, 1, nchar(scriptName) - nchar(strsplit(scriptName, '.*[/|\\]')[[1]][2]) ) 
+1
source share

All Articles