How to add quotes around each word in a string in R?

Tomás Navarro picture Tomás Navarro · Sep 1, 2015 · Viewed 12.5k times · Source

I have a string:

words<-"Monday, Tuesday, Wednesday, Thursday,Friday"

and I only need add quotes to each word:

"Monday", "Tuesday", "Wednesday", "Thursday","Friday"

getting a length of five string.

I know there are many post about this topic, but I did´t find anything about it in R.

Many thanks.

Answer

akrun picture akrun · Sep 1, 2015

We can split the words by , to get a list output. We loop through sapply , dQuote the elements and then paste it together with toString which is a wrapper for paste(..., collapse=', ').

sapply(strsplit(words, '[, ]+'), function(x) toString(dQuote(x)))
#[1] "“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”"

If we need to change the fancy quotes, add FALSE in dQuote

sapply(strsplit(words, '[, ]+'), function(x) toString(dQuote(x, FALSE)))