R Command for Setting Working Directory to Source File Location in Rstudio

R command for setting working directory to source file location in Rstudio

To get the location of a script being sourced, you can use utils::getSrcDirectory or utils::getSrcFilename. So changing the working directory to that of the current file can be done with:

setwd(getSrcDirectory()[1])

This does not work in RStudio if you Run the code rather than Sourceing it. For that, you need to use rstudioapi::getActiveDocumentContext.

setwd(dirname(rstudioapi::getActiveDocumentContext()$path))

This second solution requires that you are using RStudio as your IDE, of course.

Set the working directory to the parent folder of the script file in R

I tried the dirname(parent.frame(2)$ofile) and dirname(sys.frame(2)$ofile) method but both do not work really well with me (I am on R 3.4.1, using RStudio, and Windows 10). I tried to source it in RStudio and R GUI. Also tried to ran it from command line.

This method below from user rakensi (https://stackoverflow.com/users/1021892/rakensi) works really well for me. Credits goes to him.
Link to answer: Getting path of an R script.

Another method (test_v2.R) works for me using Rscript. Credit goes to user steamer25 (https://stackoverflow.com/users/93345/steamer25) and the link to the answer(Rscript: Determine path of the executing script).

test.R Run this using source(test.R) in Rstudio

## Run this from ~/Documents/project/code or directory of your choice
script.dir <- getSrcDirectory(function(x) {x})
print(script.dir)
# gives you ~/Documents/project/code
setwd(script.dir)

test_v2.R Run this using Rscript.exe

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))
}
}
script.dir <- dirname(thisFile())
setwd(script.dir)
print(getwd())

How can you set the working directory quickly to a file's location in RStudio?

There's a new feature on RStudio.

Just right-click on the a script's tab and choose "Set Working Directory"

Sample Image

The script has to be saved first as an R file for this to work (see this comment)

How to open next folder in working directory for only one file?

Use file.path - setwd is for setting the directory, whereas getwd returns the path of working directory.

setwd("C:/User/WorkDirectory")
read.csv(file.path(getwd(), "Folder 1", "Another 1.csv"))

Or we may also use . to signify the working directory

read.csv(file.path(".", "Folder 1", "Another 1.csv"))


Related Topics



Leave a reply



Submit