Search code examples
rstringtext

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.


Solution

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

    paste(sQuote(strings, q = FALSE), collapse = ",")
    
    [1] "'apple','banana','029'"