2

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 did it

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

then I replaced all " \ " to "/" but I got it this time:

cannot change working directory

Please help me.

4redwood
  • 365
  • 2
  • 13
sociolog
  • 83
  • 1
  • 8
  • 1
    Either `setwd("C:\\Users\\alimo\\Desktop\\DataVisualizationwithggplot2.R")` or `setwd("C:/Users/alimo/Desktop/DataVisualizationwithggplot2.R")` – r2evans Jun 20 '20 at 20:09
  • 7
    But you cannot change directory to an R file, consider `setwd("C:/Users/alimo/Desktop")` – r2evans Jun 20 '20 at 20:09
  • 1
    I now understand what you mean. And it is solved! thank you – sociolog Jun 20 '20 at 20:15

1 Answers1

4

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"))
  • 2
    (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). – r2evans Jun 20 '20 at 22:58