Reputation: 3534
I want to escape single quotation marks in a vector (for example to execute a SQL query), but I'm unable to do so.
Example code:
strings <- c("ef'gh")
strings2 <- gsub("'", "\'", strings)
cat(strings2)
print(strings2)
Expected output of either cat or print:
ef\'gh
"ef\'gh"
But none of the above. I tried multiple other combinations already, with different ways of escaping quotation, without success.
Upvotes: 1
Views: 30
Reputation: 4283
You may use the following code:
strings <- c("ef'gh")
strings2 <- sub("\'", "\\\\'", strings)
cat(strings2)
[1] ef\'gh
print(strings2)
[1] "ef\\'gh"
Upvotes: 1