How to escape backslashes in R string

匿名 (未验证) 提交于 2019-12-03 02:15:02

问题:

I'm writing strings to a file using R:

> x1="\\str" > x2="\\\str" Error: '\s' is an unrecognized escape in character string starting "\\\s" > x2="\\\\str" > write(file='test',c(x1,x2)) 

When I open the file named test, I see this:

\str \\str 

If I want to get a string containing 5 backslashes, should I write 10 backslashes, like this?

x="\\\\\\\\\\str"  

回答1:

[...] If I want to get a string containing 5 \ ,should i write 10 \ [...]

Yes, you should. To write a single \ in a string, you write it as "\\".

This is because the \ is a special character, reserved to escape the character that follows it. (Perhaps you recognize \n as newline.) It's also useful if you want to write a string containing a single ". You write it as "\"".

The reason why \\\str is invalid, is because it's interpreted as \\ (which corresponds to a single \) followed by \s, which is not valid, since "escaped s" has no meaning.



回答2:

Note that the doubling of backslashes is because you are entering the string at the command line and the string is first parsed by the R parser. You can enter strings in different ways, some of which don't need the doubling. For example:

> tmp  print(tmp) [1] "\\\\\\\\\\str" > cat(tmp, '\n') \\\\\str  >  


回答3:

Have a read of this section about character vectors.

In essence, it says that when you enter character string literals you enclose them in a pair of quotes (" or '). Inside those quotes, you can create special characters using \ as an escape character.

For example, \n denotes new line or \" can be used to enter a " without R thinking it's the end of the string. Since \ is an escape character, you need a way to enter an actual . This is done by using \\. Escaping the escape!



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!