Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert backslash followed by single quote using paste0 in R?

Tags:

r

escaping

I'm trying to separate the elements in a vector with \' and a comma using paste0. For example:

test_vector = c("test1", "test2", "test3") 

I would like to use paste0 to generate the following output:

\'test1\', \'test2\', \'test3\'

because the backslash character is an escape character itself,

paste0(test_vector, collapse = "\', \'")

generates the following:

"test1', 'test2', 'test3"

like image 840
bike freak Avatar asked Jun 14 '16 18:06

bike freak


1 Answers

How about

(x <- paste0("\\'", test_vector, "\\'", collapse = ", "))
# [1] "\\'test1\\', \\'test2\\', \\'test3\\'"

We can check the actual result with cat() (since the second backslash is only present when printed to the console).

cat(x)
# \'test1\', \'test2\', \'test3\'
like image 150
Rich Scriven Avatar answered Oct 25 '22 06:10

Rich Scriven