R 转义字符

转义字符

要在字符串中插入非法字符,必须使用转义字符。

转义字符是反斜杠 \ 后跟要插入的字符。

非法字符的例子是被双引号包围的字符串中的双引号:

实例

str <- "We are the so-called "Vikings", from the north."

str

结果:

Error: unexpected symbol in "str <- "We are the so-called "Vikings"

亲自试一试

要解决此问题,请使用转义字符 \"

实例

转义字符允许您在通常不允许的情况下使用双引号:

str <- "We are the so-called \"Vikings\", from the north."

str
cat(str)

亲自试一试

请注意:自动打印 str 变量将在输出中打印反斜杠。您可以使用 cat() 函数打印它而不带反斜杠。

R 中的其他转义字符:

代码 结果
\\ 反斜杠
\n 新行
\r 回车
\t 制表符
\b 退格