rdirectorypathread.tablewrite.table

Why R uses forward slash (/) and not backslash (\) in file paths


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!


Solution

  • 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).