Read a string with single and double quotes
Just a summer curiosity about strings in R. Let's say I have strings x
and y
. As we know, we have to cast single quotes in double quotes and vice versa.
x <- "a string with 'single' quotes"
y <- 'another one with "double" quotes'
paste0(x, y)
[1] "a string with 'single' quotesanother one with \"double\" quotes"
cat(x, y)
a string with 'single' quotes another one with "double" quotes
What if we have a single and double quoted string? I tried this: Backticks don't work (R throws an error):
z <- `a string with 'single' quotes and with "double" quotes`
Use \"
instead "
and then use cat
: This works well, but the problem is that users have to add a backslash to every double quote.
z1 <- "a string with 'single' quotes and with \"double\" quotes"
what if we have huge text (for example .txt
) with both types of quotes and we want to read in R?
At this point, the solution seems to me to be a (stupid) solution: work outside R, do some manipulation (like replacing everything "
with \"
), and then read into R. Is this a solution or is there a better way inside R?
Here is just a small file .txt
, for example: Link , anyway for anyone interested, the file is just .txt
one line with this text:
a string with "single" quotes and with "double" quotes
source to share
When reading text, you can specify any alternative quoting characters, for example
> p<-scan(what="character",quote="`")
1: `It is 'ambiguous' if "this is a new 'string' or "nested" in the 'first'", isn't it?`
2:
Read 1 item
> p
[1] "It is 'ambiguous' if \"this is a new 'string' or \"nested\" in the 'first'\", isn't it?"
Or just read the source for example. with readline
as suggested by @rawr
> readline()
"It is 'ambiguous' if "this is a new 'string' or "nested" in the 'first'", isn't it?"
[1] "\"It is 'ambiguous' if \"this is a new 'string' or \"nested\" in the 'first'\", isn't it?\""
source to share