Home » How to Use setwd / getwd in R (With Examples)

How to Use setwd / getwd in R (With Examples)

by Erma Khan

Whenever you use R, your environment is always pointed to some working directory.

You can use the following functions in R to get the working directory and set the working directory:

  • getwd() – Get the current working directory
  • setwd(‘Path/To/Some/Directory’) – Set current working directory

The following examples show how to use these functions in practice.

Example 1: Get Working Directory

We can use the getwd() function to display the current working directory in R:

#display current working directory
getwd()

[1] "C:/Users/Bob/Desktop"

Example 2: Set Working Directory

We can then use the setwd() function to set the working directory to some new location:

#set working directory
setwd('C:/Users/Bob/Documents')

We can then verify that the working directory has changed by using the getwd() function again to get the current working directory:

#display current working directory
getwd()

"C:/Users/Bob/Documents"

Example 3: View Files in Working Directory

Once we’ve set the working directory, we can use the list.files() function to view the file names within the directory:

#view number of files in working directory
length(list.files())

[1] 147

#view first five file names in working directory
head(list.files())

"output.yml"  "analysis3.R"  "analysis3-1.R"  "testdoc.R"  "final_model2.Rmd" 

We can also use the %in% operator to check if a specific file is located in our current working directory:

#check if file 'analysis3.R' exists in working directory
'analysis3.R' %in% list.files()
[1] TRUE

An output value of TRUE indicates that the specific file is indeed located in the current working directory.

Additional Resources

The following tutorials explain how to perform other common functions in R:

How to Manually Enter Raw Data in R
How to Import CSV Files into R
How to Import Excel Files into R
How to Fix in R: cannot change working directory

Related Posts