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
  • 93
  • 8

3 Answers3

1

You can escape the quotation marks using a backslash.

Check out How to display text with Quotes in R?

B.C
  • 537
  • 3
  • 15
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,788
  • 2
  • 17
  • 37
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,006
  • 3
  • 21
  • 44
  • I tried using the following code 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 – 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