Get/Set Working Directory in R
In this tutorial, we shall learn how to set R working directory and get the value of R working directory using example R scripts.
R Working Directory is the directory of R workspace. Any files in the R workspace could be referenced in R commands without specifying any relative path. While working with external input files or output files, knowing the R workspace helps in easing the efforts.
Syntax – getwd() – Get Working Directory
The syntax of R function to get working directory is
getwd()
Example 1 – Get Working Directory in R
In this example, we will use getwd() to get current working directory.
r_wd.R
# get location of working directory wd = getwd() print (wd)
Output
$ Rscript r_wd.R [1] "/home/arjun/workspace/r"
Syntax – setwd() – Set Working Directory
The syntax of R function to set working directory is
setwd(<complete_working_directory_path>)
The change to the working directory is only for scope of current running R Script. Once the current R script file execution is completed, the working directory reverts to default workspace.
Example 2 – Set Working Directory in R
In this example, we will use setwd() to set current working directory to a new path.
r_wd.R
# get location of working directory wd = getwd() print (wd) # set location of working directory setwd("/home/arjun/") # verify the working directory wd = getwd() cat("\n Working directory changed to : ", wd,"\n")
Output
$ Rscript r_wd.R [1] "/home/arjun/workspace/r" Working directory changed to : "/home/arjun"
Conclusion
In this R Tutorial, we have learnt how to set working directory and get the value of working directory using example R scripts.