amty
amty

Reputation: 123

r adding double quotes in a character string of different length

I have a character string like this ;

emergency room OR emergency medicine OR cardiology

I would like to add double quotes in all terms except 'OR'. So the final result should be

"emergency room" OR "emergency medicine" OR "cardiology"

Upvotes: 1

Views: 692

Answers (3)

Val
Val

Reputation: 7033

It's a bit of a hack, but it works just fine:

s <- 'emergency room OR emergency medicine OR cardiology'

sq <- sprintf('"%s"',paste0(str_split(s,' OR ')[[1]],collapse = '" OR "')))

cat(sq)
#"emergency room" OR "emergency medicine" OR "cardiology"

or even simpler:

sq <- sprintf('"%s"',gsub(' OR ','" OR "',s))

cat(sq)

#"emergency room" OR "emergency medicine" OR "cardiology"

Upvotes: 0

B.C
B.C

Reputation: 587

You can escape the quotation marks using a backslash.

Check out How to display text with Quotes in R?

Upvotes: 1

Terru_theTerror
Terru_theTerror

Reputation: 5017

Try this code:

cat(paste0('"',paste0(unlist(strsplit(string," OR ")),collapse='" OR "'),'"'))
"emergency room" OR "emergency medicine" OR "cardiology"

In your string you will have backslash before special character "

paste0('"',paste0(unlist(strsplit(string," OR ")),collapse='" OR "'),'"')
[1] "\"emergency room\" OR \"emergency medicine\" OR \"cardiology\""

Upvotes: 0

Related Questions