Dirk Nachbar
Dirk Nachbar

Reputation: 522

r: escape single quote in a string

I have a string like a <- "abc'def" and I need to paste this into a longer sql string:

 s <- paste0("select * from x where xx ='", a, "'")

But the single quote in the middle makes it fail, I cannot manually replace ' with \' but need to use a function.

Upvotes: 1

Views: 4234

Answers (2)

sebastian-c
sebastian-c

Reputation: 15395

In many SQL implementations, doubling achieves the escaping you want:

a <- "abc'def"
a <- gsub("'", "''", a)
s <- paste0("select * from x where xx ='", a, "'")

[1] "select * from x where xx ='abc''def'"

Upvotes: 3

Hong Ooi
Hong Ooi

Reputation: 57686

You need to escape the ' in a with something appropriate to your database, not to R. That will probably be by doubling it up: ''.

Upvotes: 3

Related Questions