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

I have a line:

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

and I only need to add quotes for each word:

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

getting a length of five lines.

I know that there are many posts about this topic, but I did not find anything about it in R.

Many thanks.

+4
source share
3 answers

We can break the words into ,to get a conclusion list. We iterate over the elements sapply, dQuoteand then pastetogether with toString, which is a wrapper for paste(..., collapse=', ').

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

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 the word boundary, which matches between the word character (AZ, az, _, 0-9) and the non-primary character (not A-Za-z0-9_) or vice versa ..

+3

strsplit , sub .

paste(dQuote(sub(" ","",unlist(strsplit(words,split = ",")))),collapse = ", ")

[1] ""Monday", "Tuesday", "Wednesday", "Thursday", "Friday""
0
source

All Articles