Reputation: 52268
Is there a way to create a string from some text that contains both single '
and double "
quote characters?
Suppose we some text containing both single and double quotes (presume an actual use case would be much longer):
Here's a message: "hello, world!"
Wrapping it in '
, or "
doesn't work:
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"
I can think of two ways that would probably work. 1. Dump the text into RStudio (or a text editor) and find and replace. 2. Paste into a text file and read in the lines with readLines()
. I just wanted to see if there's an easier way
Upvotes: 6
Views: 1008
Reputation:
If you have a version 4.0.0 or later R, you can use r"(all of your text here)"
.
text <- r"(My text "has" double and 'single' quotes)"
> cat(text)
My text "has" double and 'single' quotes
Documentation for this can be found by running help("Quotes")
.
Upvotes: 8
Reputation: 1604
You can simply escape the characters using backslash "":
thing <- "Here's a message: \"hello, world!\""
now you can print the variable using cat:
cat(thing)
don't worry if the R console shows the backslash characters, because they not actually part of the string
> xx <- "\""
> xx
[1] "\""
> length(xx)
[1] 1 # you see it is just one character! :)
Upvotes: 2
Reputation: 61933
If you're inputting directly into the console then you'll just want to escape the quotes using a backslash. Here's an example:
> 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!"
Upvotes: 2