0

I want to concatenate the items of a character vector:

vector<-c("Hello", "World", "Today") vector [1] "Hello" "World" "Today" 

I want to insert a comma between all the items and maintain the ("") of each character. The final result should look like this:

"Hello","World","Today" 

Is it possible to do this in R, I tried with paste and paste0, but so far without any luck!

1
  • 1
    paste(vector,collapse = ",") will work, but do not name vector's vector because it is a function in R. Commented Apr 8, 2019 at 18:14

3 Answers 3

3

This is one way. Notice that the "s are escaped when they are part of a character string.

v <- c("Hello", "World", "Today") v2 <- paste0("\"", v, "\"", collapse=", ") cat(v2) # "Hello", "World", "Today" 
Sign up to request clarification or add additional context in comments.

1 Comment

Note, you can also use '"' - instead of escaping "\"" - ?Quotes has lots more information.
2

1) Use shQuote to add double quotes and then toString to insert comma space between them:

toString(shQuote(v)) ## [1] "\"Hello\", \"World\", \"Today\"" 

2) If it's important that there be no space then:

paste(shQuote(v), collapse = ",") ## [1] "\"Hello\",\"World\",\"Today\"" 

3) Another approach is via sprintf (or use paste as above):

toString(sprintf('"%s"', v)) ## [1] "\"Hello\", \"World\", \"Today\"" 

Note that the backslashes are not actually in the strings but are just shown by print so you know that the following double quote is part of the string as opposed to a delimiter that signals the end of the string.

1 Comment

Thanks for your clarifying answer, I wasn t aware of those functions!
0

It is worth pointing out that even though you see " characters when you print your vector, these characters are not actually part of the vector - they are just shown by R as a convenient way to show the individual strings in a character vector. We can see this if we use cat to display the contents of the vector as-is.

v <- c("Hello", "World", "Today") cat(v) #Hello World Today 

Depending on your use case, it is quite likely that you don't really need to embed actual commas and quotes into the data, but rather to just have them displayed when you print. If this is the desired effect, you can achieve it by defining a new class for these vectors and a print method to determine how they get displayed:

class(v) = c('comma') print.comma = function(x,...) cat(paste0('"',x,'"', collapse = ',')) v # "Hello","World","Today" 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.