Home > Back-end >  How to add single quotes around multiple strings
How to add single quotes around multiple strings

Time:09-29

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.

CodePudding user response:

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

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

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

CodePudding user response:

Using sprintf.

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

or

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