I want to make the current file location as the working directory.
Using Rstudio (Works!):
# Author : Bhishan Poudel
# Program :
I write another answer because you changed your question. There are two useful facts:
ofile
is a variable in the environment of the source
function, so you can use it only when you run some script with the source
function.So, to comment on your observations:
source
function), but not if you press Run (which just runs the commands in the R console).ofile
without a call to source
.this_dir <- function(directory) setwd( file.path(getwd(), directory) )
is needless as it is just the definition of a function called this_dir
.setwd_thisdir
is needless because it just prints the body of setwd_thisdir
to the console.In summary setwd(dirname(parent.frame(2)$ofile))
is a useful trick when you source a script with the source
function, but don't have access to the source
function options: e.g. when you press Source in R-Studio. When possible use intead the source
function with chdir=TRUE
. If you run the script form the terminal just set the terminal to the script folder.