-2

I have a data set that I'd like to add quote marks to based on three rules:

  1. add quote marks before and after any =
  2. add a quote mark after any ( and before any )
  3. add a quote mark before and after any ,

For example

Input ->   (Ten + Four = Fourteen, Two - One = 1)
Output ->  "("Ten + Four"="Fourteen", "Two - One"="1")"

I must over-engineering this and was wondering if anyone had a good trick in base r?

nicshah
  • 345
  • 1
  • 8

1 Answers1

0

You can use gsub and nest it. Since you wanted base I did one nesting for you. For more elegant methods you can check here

foo <- c( "i = 2", "i , 2", " ( i 2 )")

#insert "="
foo2 <- gsub('=', '\"=\"', foo)
#insert ","
foo2 <- gsub(',', '\",\"', foo2) 
#insert "( and )"
foo2 <- gsub('\\)', '"\\)', foo2)
foo2 <- gsub('\\(', '\\("', foo2)

#same expression but nested.
foo2<- gsub('=', '\"=\"', gsub(',', '","', gsub('\\(', '\\("', gsub('\\)', '"\\)', foo))))

output:

cat(foo2)


i "=" 2   i "," 2    (" i 2 ")

amendment:

If you are putting your output through console you will get \" as output for ". This is basically the same. The console shows you the source code in this case.

'"' == '\"'
mischva11
  • 2,811
  • 3
  • 18
  • 34