简体   繁体   English

为什么 R 在文件路径中使用正斜杠 (/) 而不是反斜杠 (\)

[英]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.我正在教一个在线课程,一个学生问我为什么 R 在使用read.csv和其他相关功能时只在文件路径中使用/而不是\ 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.从来没有真正考虑过,因为我使用的是 Mac,Mac 中的默认值是\ ,但在 Windows 机器中不是这样。

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!学生们总是问最糟糕的事情!

Interesting question.有趣的问题。

First off, the "forward slash" / is actually more common as it used by Unix, Linux, and macOS.首先,“正斜杠” /实际上更常见,因为它被 Unix、Linux 和 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" .因此,无论何时需要,都需要在字符串中输入两个: "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!第三,Windows 上的 R 知道这一点并提供帮助:因此,您可以在使用反斜杠的任何地方使用正斜杠: "C:/TEMP"的工作原理相同!

Fourth, you can have R compute the path for you and it will use use the separator: file.path("some", "dir") .第四,您可以让 R 为您计算路径,它将使用分隔符: file.path("some", "dir")

So the short answer: R uses both on Windows and lets you pick whichever you find easier.所以简短的回答:R 在 Windows 上同时使用,让你选择你觉得更容易的那个。 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).但请记住使用两个反斜杠(除非您在原始字符串上使用非常新的 R 4.0.0 功能,我现在将跳过)。

(Note: backslashes as directory folder separators on Macs is a recent innovation.See History of Mac folder separators (注意:反斜杠作为 Mac 上的目录文件夹分隔符是最近的一项创新。参见 Mac 文件夹分隔符的历史

I think if you review the history (or look it up if you were not there when it occurred as I was) you will find that Unix (which Linux copied completely) got there first.我认为,如果您查看历史记录(或者如果您在它发生时不在那里进行查找),您会发现 Unix(Linux 完全复制)首先到达那里。 It preceded either MS-DOS or Macs or last of all Windows.它先于 MS-DOS 或 Mac 或最后一个 Windows。 R is a work-alike clone of S which was developed like Unix at Bell Labs. R 是 S 的一个类似工作的克隆,它像贝尔实验室的 Unix 一样开发。

Mac originally used colons (:) as folder separators (and still won't accept them in file names) and converted to slashes sometime during its long transition to BSD Unix which it licensed from ATT. Mac 最初使用冒号 (:) 作为文件夹分隔符(并且仍然不会在文件名中接受它们),并在其长期过渡到从 ATT 许可的 BSD Unix 期间的某个时间转换为斜杠。

Shouldn't the question be: why Microsoft chose to use a backslash?问题不应该是:为什么微软选择使用反斜杠?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM