string 如何在 R 中显示带引号的文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15204442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:49:49  来源:igfitidea点击:

How to display text with Quotes in R?

stringrquotes

提问by knix2

I have started learning R and am trying to create vector as below:

我已经开始学习 R 并尝试创建如下向量:

c(""check"")

I need the output as : "check". But am getting syntax error. How to escape the quotes while creating a vector?

我需要输出为:“检查”。但我收到语法错误。创建向量时如何转义引号?

回答by A5C1D2H2I1M1N2O1R2T1

As @juba mentioned, one way is directly escaping the quotes.

正如@juba 提到的,一种方法是直接转义引号。

Another way is to use single quotes around your character expression that has double quotes in it.

另一种方法是在包含双引号的字符表达式周围使用单引号。

> x <- 'say "Hello!"'
> x
[1] "say \"Hello!\""
> cat(x)
say "Hello!"

回答by regetz

Other answers nicely show how to deal with double quotes in your character strings when you create a vector, which was indeed the last thing you asked in your question. But given that you also mentioned displayand output, you might want to keep dQuotein mind. It's useful if you want to surround each element of a character vector with double quotes, particularly if you don't have a specific need or desire to store the quotes in the actual character vector itself.

其他答案很好地展示了在创建向量时如何处理字符串中的双引号,这确实是您在问题中提出的最后一件事。但鉴于您还提到了displayoutput,您可能要dQuote记住。如果您想用双引号将字符向量的每个元素括起来,这很有用,特别是如果您没有特定的需要或希望将引号存储在实际的字符向量本身中。

# default is to use "fancy quotes"
text <- c("check")
message(dQuote(text))
## “check”

# switch to straight quotes by setting an option
options(useFancyQuotes = FALSE)
message(dQuote(text))
## "check"

# assign result to create a vector of quoted character strings
text.quoted <- dQuote(text)
message(text.quoted)
## "check"

For what it's worth, the sQuotefunction does the same thing with single quotes.

对于它的价值,该sQuote函数用单引号做同样的事情。

回答by juba

Use a backslash :

使用反斜杠:

x <- "say \"Hello!\""

And you don't need to use cif you don't build a vector.

c如果不构建向量,则不需要使用。

If you want to output quotes unescaped, you may need to use catinstead of print:

如果要输出未转义的引号,则可能需要使用cat代替print

R> cat(x)
say "Hello!"