4

I get "cannot change working directory" error when I try to set up my working directory:

setwd("C:\Users\alimo\Desktop\DataVisualizationwithggplot2.R")
*Error: '\U' used without hex digits in character string starting ""C:\U"*

then I ran:

options(PACKAGE_MAINFOLDER="C:/Users/...")

and replaced all "" to "/" but I got this error this time:

cannot change working directory
2
  • 1
    Either setwd("C:\\Users\\alimo\\Desktop\\DataVisualizationwithggplot2.R") or setwd("C:/Users/alimo/Desktop/DataVisualizationwithggplot2.R") Commented Jun 20, 2020 at 20:09
  • 9
    But you cannot change directory to an R file, consider setwd("C:/Users/alimo/Desktop") Commented Jun 20, 2020 at 20:09

1 Answer 1

7

Yes, writing a path to a file or directory can sometimes be a bit painful, especially when you move across different platforms!

setwd() sets the working directory, so it means you need to specify a directory, not a file.

And whenever I'm not sure about the single/double (back)slashes, I like to use file.path() from base R, which adds a correct delimiter in a platform-independent way:

file.path("~", "myfolder", "myfile.R")

So for your case:

setwd(file.path("C:", "Users", "alimo", "Desktop"))
Sign up to request clarification or add additional context in comments.

1 Comment

(1) double-backslashes are only required if the user chooses to use backslashes; on Windows, R will accept either, so there really is no need to type in backslashes (though other commands/env-vars will still contain backslashes). (2) Good use of file.path, further good to know is that it has an argument fsep= which defaults to \` on windows and /` everywhere else. When I use file.path, even on windows I almost always use fsep="/" since backslashes hurt my eyes. However, once can always get the file-sep with .Platform$file.sep (default value for file.path, btw).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.