从包含单引号和双引号的字符创建字符串?

时间:2021-02-19 16:38:56

标签: r

有没有办法从包含单 ' 和双 " 引号字符的文本创建字符串?

示例

假设我们有一些包含单引号和双引号的文本(假设实际用例会更长):

Here's a message: "hello, world!"

将其包裹在 '" 中不起作用:

thing <- "Here's a message: "hello, world!""
Error: unexpected symbol in "thing <- "Here's a message: "hello"

thing <- 'Here's a message: "hello, world!"'
Error: unexpected symbol in "thing <- 'Here's"

我能想到两种可能有效的方法。 1. 将文本转储到 RStudio(或文本编辑器)并查找和替换。 2. 粘贴到一个文本文件中并读入带有 readLines() 的行。我只是想看看有没有更简单的方法

3 个答案:

答案 0 :(得分:5)

如果您有 4.0.0 或更高版本的 R,则可以使用 r"(all of your text here)"

text <- r"(My text "has" double and 'single' quotes)"

> cat(text)
My text "has" double and 'single' quotes

可以通过运行 help("Quotes") 找到相关文档。

答案 1 :(得分:2)

如果您直接输入到控制台,那么您只想使用反斜杠转义引号。举个例子:

> text <- "Here\'s a message: \"hello, world!\""
> cat(text, "\n") # Adding a new line so the prompt doesn't mess things up
Here's a message: "hello, world!" 

答案 2 :(得分:2)

您可以简单地使用反斜杠“”来转义字符:

thing <- "Here's a message: \"hello, world!\""

现在您可以使用 cat 打印变量:

cat(thing)

不要担心 R 控制台是否显示反斜杠字符,因为它们实际上不是字符串的一部分


> xx <- "\""
> xx
[1] "\""

> length(xx)
[1] 1 # you see it is just one character! :)