1

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"

amty
  • 113
  • 1
  • 10

3 Answers3

1

You can escape the quotation marks using a backslash.

Check out How to display text with Quotes in R?

B.C
  • 577
  • 3
  • 18
0

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\""
Terru_theTerror
  • 4,918
  • 2
  • 20
  • 39
0

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"
Val
  • 6,585
  • 5
  • 22
  • 52
  • I tried using the following code sq <- sprintf('"%s"',gsub(' OR ','" OR "',s)) cat(sq) But, I am not able to assign the result of above expression to a new object. So in continuation of your code when i use finalkeywords <- cat(sq) > finalkeywords NULL I do not understand why this is happening? – amty Mar 08 '18 at 19:50
  • `cat` is only outputs the string to the console, so running `finalkeywords <- cat(sq)` will result in `NULL` - the important part is `sprintf('"%s"',gsub(' OR ','" OR "',s))`, with `s` being your string which needs double quotes – Val Mar 08 '18 at 19:58
  • You can't assign the output of `cat` to a variable. Double quotes in a string in `R` need to be escaped with a backslash, hence `\"` is the correct representation - you can see that if you just run `sq` or `print(sq)` – Val Mar 08 '18 at 20:00
  • I am sorry. I understood your point that cat only outputs the string to the console. But my point is how can I assign the resulting string with double quotes to a new object? – amty Mar 08 '18 at 20:02
  • in `R`, `\"Hello World\"` would be the accurate character string of "Hello World" – Val Mar 08 '18 at 20:06
  • Undestood @Val. Thank you so much for putting so much efforts. – amty Mar 08 '18 at 20:10
  • Glad I could help! – Val Mar 08 '18 at 20:11