How to set the current file location as the default working directory in R programming?

BhishanPoudel picture BhishanPoudel · Jan 29, 2016 · Viewed 16.1k times · Source

I want to make the current file location as the working directory.

Using Rstudio (Works!):

# Author  : Bhishan Poudel
# Program : writehere.r
# Source  : Rscript writehere.r

# set working directory here
this.dir <- dirname(parent.frame(2)$ofile) # frame(3) also works.
setwd(this.dir)

# Sample data to test this code
mydata <- seq(1:10)
write.csv(mydata,"writehere.dat")
#This works flawlessly in  MacOS 10.9 and Ubuntu 15.1.

Using Command from terminal : Rscript writehere.r (Does not work!)

Error in dirname(parent.frame(2)$ofile) : 
  a character vector argument expected
Execution halted


------------------
(program exited with code: 1)

Using Command from terminal : Rscript writehere.r (Works now!)

# Author  : Bhishan Poudel
# Program : writehere.r
# Source  : Rscript example.r

# set working directory here
this_dir <- function(directory)
setwd( file.path(getwd(), directory) )

# Sample data to test this code
mydata <- seq(1:10)
write.csv(mydata,"writehere.dat")

Using function inside ~/.Rprofile for Rstudio (Works!) :,

##############################################
# inside ~/.Rprofile
# set up working directory
setwd_thisdir <- function () {
  this.dir <- dirname(parent.frame(3)$ofile)
  setwd(this.dir)
} 
##############################################

Then, in any directory let's say I have a file writehere.r, now it works.

# Author  : Bhishan Poudel
# Program : writehere.r
# Compile : Rscript writehere.r

# set working directory here
setwd_thisdir

# Sample data to test this code
mydata <- seq(1:10)
write.csv(mydata,"writehere.dat")

Question: Why the function

this.dir <- dirname(parent.frame(2)$ofile) # frame(3) also works.
setwd(this.dir)

does not work for text editors other than Rstudio?

Some useful links are following:
R setting working directory to source file location?
R command for setting working directory to source file location
get filename and path of `source`d file
setwd() in the current working dir
Command for "Set working directory to source file location"
SublimeText and R: Setting Current File Directory
Setting working directory through a function
What is a fool-proof way of permanently setting R working directory?
R setting working directory to source file location?
How to get into the directory of a file in R?

Answer

Suresh Gautam picture Suresh Gautam · Aug 31, 2019

Simply, use rstudio API, extract its directory, and set it as a working directory as shown below:

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

Verify if you set the directory correctly by the following command:

getwd()