Search code examples
rstringstring-concatenation

Concatenate strings with quotation marks separated by commas


I want to write a function that concatenates multiple strings into one one string, but each part is marked with quotation marks and separated by a comma.

The function should basically take the inputs "a"and "b" and print this c('"a", "b"'), which will result in an output like this:

c('"a", "b"')

# [1] "\"a\", \"b\""

How can I created this c('"a", "b"') in a function body?


Solution

  • You can achieve it by a single paste0():

    x <- c("a", "b", "c")
    
    paste0('"', x, '"', collapse = ", ")
    
    # [1] "\"a\", \"b\", \"c\""
    

    or sprintf() + toString():

    toString(sprintf('"%s"', x))
    # [1] "\"a\", \"b\", \"c\""