35

Using R, I want to produce multiple character strings such as:

"modelCheck("var1_d.bug")"  
"modelCheck("var2_d.bug")"  
...  
"modelCheck("var10_d.bug")"

I would usually use a for loop and paste (if I did not have to worry about the double quotation marks) as such:

for(i in 1:10){
    str<-paste("modelCheck(var",i,"_d.bug)",sep="")
    print(str)
}

However, I need to include the double quotation marks within the character string, hence the appeal for help?

Jubbles
  • 4,450
  • 8
  • 35
  • 47
guyabel
  • 8,014
  • 6
  • 57
  • 86

1 Answers1

57

Simply escape the quotation marks with backslashes:

paste("modelCheck(var\"",i,"_d.bug\")",sep="")

An alternative is to use single quotes to enclose the string:

paste('modelCheck(var"',i,'_d.bug")',sep="")
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • 14
    This is giving me output that includes the double quotation, but also includes the slash: "modelCheck(\"var1_d.bug\")". How to escape the escape? – guyabel Dec 15 '10 at 18:03
  • 6
    The backslash is not part of the string, it's simply printed that way. You can verify by counting the characters by hand and comparing with `length(result)`. More importantly, what exactly are you trying to do? – NPE Dec 15 '10 at 18:21
  • Interesting. I am trying to create lots of openbugs script files to send different models (var1.bug, var2.bug, ...) to our computing cluster. I am using writeLines command in R to create these script files quickly. The escape seems to works properly for this purpose (having just tested it). I wonder why R shows the slash when using print though? – guyabel Dec 15 '10 at 18:37
  • This seems pretty consistent of R, but I can see arguments both ways. There may be a way to suppress the backslash when displaying on screen, but I don't know what it is. – NPE Dec 15 '10 at 18:42
  • 12
    If you use cat() you should get un-escaped output. Come on gjable, aix answered your question ... give it the "check". – IRTFM Dec 15 '10 at 21:34
  • It also doesnt work for me with the escape. I have to evaluate the string afterworth, which makes this problematic. – Esben Eickhardt Apr 24 '17 at 14:08