How to Fix in R: cannot change working directory

One error you may encounter in R is:

Error in setwd("C:/Users/UserName/Desktop") : 
  cannot change working directory

This error occurs when you attempt to set the working directory in R, but you misspell some part of the file path.

This tutorial shares exactly how to fix this error.

How to Reproduce the Error

Suppose I attempt to set the following working directory in R:

#attempt to set working directory
setwd("C:/Users/Bob/Documents/My Folder Name")

Error in setwd("C:/Users/Bob/Documents/My Folder Name") : 
  cannot change working directory

I receive an error because this folder does not exist on my computer.

How to Fix the Error

The easiest way to fix this error is to change the file path to point to the correct folder:

#set working directory
setwd("C:/Users/Bob/Documents/Correct Folder Name")

Notice that I don’t receive an error because R was able to successfully change the working directory.

I can confirm that the working directory successfully changed by using the getwd() function to get the current working directory:

#get current working directory

"C:/Users/Bob/Documents/Correct Folder Name"

Common Reasons for Errors

There are several reasons for why you may receive this error message in R. Common reasons include:

  • You simply misspelled the file path.
  • You included invalid characters in the file path.
  • You do not have permission to access the file path.

If you run into this error, make sure to check these three common issues and fix them if necessary.

Additional Resources

The following tutorials explain how to fix other common errors in R:

How to Fix: NAs Introduced by Coercion
How to Fix: missing value where true/false needed
How to Fix: incorrect number of subscripts on matrix
How to Fix: number of items to replace is not a multiple of replacement length

Leave a Reply

Your email address will not be published. Required fields are marked *