在R中有效地将反斜杠转换为正斜杠 [英] Efficiently convert backslash to forward slash in R
问题描述
我正在寻找一种将R中的反斜杠转换为正斜杠的有效方法。有时,我在Windows中复制目录的链接,会得到如下信息:
I am looking for an efficient way to convert back slash to forward slash in R. Sometime I copy the link of the directory in Windows and I get something like this:
C:\Users\jd\Documents\folder\file.txt
如何快速将其更改为 C:/Users/jd/Documents/folder/file.txt
?我什至无法将以上表达式理解为字符。会引发错误
How can I quickly change this to C:/Users/jd/Documents/folder/file.txt
? I cannot even read the above expression as character. It throws an error
\u,字符串中以 C:quotu开头没有十六进制数字。
"\u used without hex digits in character string starting ""C:\u".
我知道R中的TAB函数有助于快速找到位置,但是只是想知道是否还有其他解决方法。我也可以将工作目录更改为文件夹的位置。我只是在玩耍,试图将反斜杠转换为正斜杠,并没有直截了当,所以只是出于好奇而问这个。
I know TAB function in R helps to find the location fast, but was just wondering if there was any other work around. I could change the working directory to the location of folder also. I was just playing around and tried to convert backslash to forward slash and was not straight forward so asked this just because of curiosity.
推荐答案
在R中,您必须使用 \\
转义 \
因此,您的路径应为:
In R, you've to escape the \
with \\
So, your path should be:
x <- "C:\\Users\\jd\\Documents\\folder\\file.txt"
要做到这一点,您可以执行以下操作:
To get that, you can do:
x <- readline()
然后在提示符下粘贴您的未修改路径(按CTRL + V然后按ENTER)
then, at the prompt, paste your unmodified path (CTRL+V then ENTER)
最后,更改 \\
到 /
的任何地方,都可以使用 gsub
,再一次转义 \
,但两次,如下所示:
Finally, to change \\
to /
everywhere, you could use gsub
, once again by escaping the \
, but twice, as follows:
gsub("\\\\", "/", x)
# [1] "C:/Users/jd/Documents/folder/file.txt"
这篇关于在R中有效地将反斜杠转换为正斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!