How to add quotes around each word in a string in R?
Use gsub
words<-"Monday, Tuesday, Wednesday, Thursday,Friday"
cat(gsub("(\\w+)", '"\\1"', words))
# "Monday", "Tuesday", "Wednesday", "Thursday","Friday"
KISS....
cat(gsub("\\b", '"', words, perl=T))
#"Monday", "Tuesday", "Wednesday", "Thursday","Friday"
\\b
called word boundary which matches between a word character (A-Z,a-z,_,0-9) and a non-word character (not of A-Za-z0-9_) or vice-versa..
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)))