Sometimes it is necessary to find or set a working directory in R, even if you don’t necessarily want to. For example, if you are saving an R plot and do not understand where the result goes, it is necessary to look for that. You can do working directory detection or setup using the base R or RStudio interface.
Get or set the working directory in R
You can use the base function getwd to find the working directory in R.
getwd()
If you want to use a different directory, use the base function setwd to set that.
setwd("C:\\Users\\dc\\Downloads\\")
If you are getting the error message “cannot change working directory“, pay attention to the path. There main reason for that error is that path doesn’t exist. If you are a Windows user, be sure that the path is specified correctly.
Suppose you want to set the R working directory to Onedrive. In that case, it might be necessary to detect the username and build the path to the directory like in this post about reading Excel files in R. Here is how to get the current username.
Sys.getenv("USERNAME")
Get or set the working directory in RStudio
If you are using RStudio, there is possible to do the same as previously using GUI. In the Session section, choose the set working directory and decide where it will be.
As you can see, there is also an RStudio shortcut for setting the working directory. If you want to know more RStudio shortcuts and quick tips, I highly recommend you my favorite ones.
Set the R working directory to the current source file location
If you want to set the working directory to the current file location, there is a previously seen option in the RStudio user interface. It is also possible to detect and use the current R script location, and here is more about that. How to get that in RStudio is in the example below.
paste( dirname(rstudioapi::getSourceEditorContext()$path), basename(rstudioapi::getSourceEditorContext()$path), sep = '/' )
List files in the R working directory
If you want to get a list of files in the working directory with the specific file type, then here is how to do that for Excel files.
list.files( path = getwd(), pattern = "*.xlsx", full.names = TRUE, recursive = FALSE )
In addition, there are two use cases from this blog. The first is combining Excel files or RDS files, and the second is the conversion of image file format in R.
Sometimes it is necessary to specify the location of R libraries, and here is how to do that.
Leave a Reply