Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put \' in my string using paste0 function [duplicate]

Tags:

string

r

paste

I have an array:

t <- c("IMCR01","IMFA02","IMFA03")

I want to make it look like this:

"\'IMCR01\'","\'IMFA02\'","\'IMFA03\'"

I tried different ways like:

paste0("\'",t,"\'")
paste0("\\'",t,"\\'")
paste0("\\\\'",t,"\\\\'")

But none of them is correct. Any other functions are OK as well.

like image 890
Feng Chen Avatar asked Mar 09 '23 03:03

Feng Chen


1 Answers

Actually your second attempt is correct:

paste0("\\'",t,"\\'")

If you want to tell paste to use a literal backslash, you need to escape it once (but not twice, as you would need within a regex pattern). This would output the following to the console in R:

[1] "\\'IMCR01\\'" "\\'IMFA02\\'" "\\'IMFA03\\'"

The trick here is that the backslash is even being escaped by R in the console output. If you were instead to write t to a text file, you would only see a single backslash as you wanted:

write(t, file = "/path/to/your/file.txt")

But why does R need to escape backslash when writing to its own console? One possibility is that if it were to write a literal \n then this would actually be interpreted by the console as a newline. Hence the need for eacaping is still there.

like image 200
Tim Biegeleisen Avatar answered Mar 10 '23 23:03

Tim Biegeleisen