Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 799
Tomás Navarro Avatar asked Sep 01 '15 11:09

Tomás Navarro


People also ask

How can I add double quotes to a string in R?

How can I add double quotes to a string taken from a vector in R? If you do paste0, you will get rid of the spaces between the quotes and your string. The shQuote is used for escaping a command passed to a shell. It should not be used for just simple quoting. Show activity on this post. The above will work on Windows.

How to append a string in R?

To append a string in R, use the paste () function. The paste () is a built-in function that concatenates or appends two or more strings. To concate strings in R, use the paste () function. The x is an R object.

How can I display a string with quotes without backslashes?

If you want to display a string containing quotes without seeing the backslashes try cat (shQuote ("blah"), " ") . I am trying this way...but my prob is output is 'blah' not "blah". I need the same result. Is there any other way.

Is there a way to give double quotes on Windows 10?

The above will work on Windows. Use shQuote ("blah", "cmd") if you need it to work the same way giving double quotes on all operating systems. Almost, the problem is that I need exactly "blah" as a result not ""blah"".


1 Answers

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..

like image 114
Avinash Raj Avatar answered Oct 07 '22 17:10

Avinash Raj