Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an R equivalent of other languages triple quotes?

Tags:

r

system

cat

I know you can escape special characters with "\"'s, but I'm interesting in creating commands that will go to the terminal that include special characters, and these cannot read the backslashes well.

As a simplified example, I'd like to have a command that looks like:

echo hello "w" or'l'd

Which could be achieved by something like

system(command="""echo hello "w" or'l'd""")

But R doesn't handle triple quotes. Is there another way? Even catching the output from cat() would be ok. e.g. newCommand = cat("echo hello \"w\" orld")

Thanks.

like image 356
Hillary Sanders Avatar asked Oct 16 '13 20:10

Hillary Sanders


People also ask

What does 3 quotation marks mean?

The triple quotation is a nice way to be able to include other types of quotation within your string without having to use escape characters. For example: print("He said \"my name's John\"") That example requires escape characters \" to use double quote marks.

Does R Use single or double quotes?

They can be used interchangeably but double quotes are preferred (and character constants are printed using double quotes), so single quotes are normally only used to delimit character constants containing double quotes.

What is a triple quote in Python?

String literals inside triple quotes, """ or ''', can span multiple lines of text. Python strings are "immutable" which means they cannot be changed after they are created (Java strings also use this immutable style).


1 Answers

You can escape the " with \". I would also use shQuote if your intention is to run system commands. It takes care of the relevant escaping for you...

shQuote( "hello \"w\" orld" , type = "cmd" )
#[1] "\"hello \\\"w\\\" orld\""

You should be aware that what you see on-screen in the R interpreter is not exactly what the shell will see.. e.g.

paste0( "echo " , shQuote( "hello \"w\" orld" , type = "sh") )
#[1] "echo 'hello \"w\" orld'"

system( paste0( "echo " , shQuote( "hello \"w\" orld" , type = "sh") ) )
#hello "w" orld
like image 171
Simon O'Hanlon Avatar answered Oct 26 '22 14:10

Simon O'Hanlon