Reputation: 170
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.
Upvotes: 13
Views: 22722
Reputation: 887851
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)))
Upvotes: 15
Reputation: 837
strsplit splits string by comma, and sub removes white spaces.
paste(dQuote(sub(" ","",unlist(strsplit(words,split = ",")))),collapse = ", ")
[1] "“Monday”, “Tuesday”, “Wednesday”, “Thursday”, “Friday”"
Upvotes: 4
Reputation: 174836
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..
Upvotes: 9