How to display text with Quotes in R? [duplicate]

核能气质少年 提交于 2019-11-28 00:04:30

问题


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

c(""check"")

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


回答1:


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

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!"



回答2:


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 display and output, you might want to keep dQuote in 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.

# 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 sQuote function does the same thing with single quotes.




回答3:


Use a backslash :

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

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

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

R> cat(x)
say "Hello!"


来源:https://stackoverflow.com/questions/15204442/how-to-display-text-with-quotes-in-r

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