Theodore Kapellos
Theodore Kapellos

Reputation: 1

How to concatenate items of a string maintaining the (" ")

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!

Upvotes: 0

Views: 123

Answers (3)

dww
dww

Reputation: 31452

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"

Upvotes: 0

G. Grothendieck
G. Grothendieck

Reputation: 269421

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.

Upvotes: 2

AkselA
AkselA

Reputation: 8837

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"

Upvotes: 3

Related Questions