Adrian
Adrian

Reputation: 9793

How to add single quotes around multiple strings

strings <- c("apple", "banana", "029")
> strings
[1] "apple"  "banana" "029"

I would like to add single quotes to each element in strings and separate the strings with ,. My desired output is this:

desired_strings <- "'apple','banana','029'"
> desired_strings
[1] "'apple','banana','029'"

My attempt:

a <- "'"
paste0(mapply(paste0, a, strings, a), ",")
[1] "'apple',"  "'banana'," "'029',"

However, this is not quite right.

Upvotes: 0

Views: 160

Answers (2)

jay.sf
jay.sf

Reputation: 72593

Using sprintf.

toString(sprintf("'%s'", strings))
# [1] "'apple', 'banana', '029'"

or

paste(sprintf("'%s'", strings), collapse=",")
# [1] "'apple','banana','029'"

Upvotes: 0

lroha
lroha

Reputation: 34291

You can use sQuote() and then collapse to a single string with paste():

paste(sQuote(strings, q = FALSE), collapse = ",")

[1] "'apple','banana','029'"

Upvotes: 3

Related Questions