3

I was teaching an online course and a student asked me why R only uses / and not \ in file paths when using read.csv and other related functions. I tried looking at the documentation but it didn’t really mention anything about it. Never really thought about it because I use a Mac, and the default in Macs is \, but not so in Windows machines.

I’m not trained in computer science so I was left a bit stumped to answer the question a I’m afraid. Students always ask the darnest things!

Henrik
  • 61,039
  • 13
  • 131
  • 152
Lalochezia
  • 467
  • 2
  • 14
  • 1
    You already have a nice answer, but I just add two links which have been useful to me and my students when discussing this topic: [Difference between forward slash (/) and backslash (\) in file path](https://stackoverflow.com/questions/38428561/difference-between-forward-slash-and-backslash-in-file-path) (not R specific); [Escaping \ in string or paths in R](https://stackoverflow.com/a/14185627/1851712). Cheers – Henrik Jul 23 '20 at 11:19
  • @Henrik Thanks for that! I quite liked the history in the first link, enough detail for me to understand it and try to explain to the student. – Lalochezia Jul 23 '20 at 11:27

1 Answers1

5

Interesting question.

First off, the "forward slash" / is actually more common as it used by Unix, Linux, and macOS.

Second, the "backward slash" \ is actually somewhat painful as it is also an escape character. So whenever you want one, you need to type two in string: "C:\\TEMP".

Third, R on Windows knows this and helps! So you can you use a forward slash whereever you would use a backward slash: "C:/TEMP" works the same!

Fourth, you can have R compute the path for you and it will use use the separator: file.path("some", "dir").

So the short answer: R uses both on Windows and lets you pick whichever you find easier. But remember to use two backward slashes (unless you use the very new R 4.0.0 feature on raw strings which I'll skip for now).

Dirk Eddelbuettel
  • 347,098
  • 55
  • 623
  • 708
  • I think this will actually be my main use case for raw strings. I often copy paths from the windows explorer and just wrapping these in `r"(...)"` is so much easier than what I have been doing so far. – Roland Jul 23 '20 at 06:32
  • Thanks for that! So what’s an escape character? – Lalochezia Jul 23 '20 at 11:26
  • See e.g. the second link I posted above. – Henrik Jul 23 '20 at 11:31
  • Thanks for adding the links, @Henrik. And yes, raw strings are awesome. Small price is the dependency on R >= 4.0.0. Old R 3.* installations are still out there a lot. No issue for local work. – Dirk Eddelbuettel Jul 23 '20 at 11:52