5

I'm having a problem with using double quotes while formatting text strings being sent to functions in R.

Consider an example function code:

foo <- function( numarg = 5, textarg = "** Default text **" ){ 
    print (textarg)
    val <- numarg^2 + numarg
    return(val) 
}

when running with the following input:

foo( 4, "Learning R is fun!" )

The output is:

[1] "Learning R is fun!"
[1] 20

But when I try (in various ways, as suggested here) to write "R" instead of R, I get the following outputs:

> foo( 4, "Learning R is fun!" )
[1] "Learning R is fun!"
[1] 20
> foo( 4, "Learning "R" is fun!" )
Error: unexpected symbol in "funfun( 4, "Learning "R"
> foo( 4, "Learning \"R\" is fun!" )
[1] "Learning \"R\" is fun!"
[1] 20
> foo( 4, 'Learning "R" is fun!' )
[1] "Learning \"R\" is fun!"
[1] 20

Using as.character(...) or dQuote(...) as suggested here seems to break the function because of different number of arguments.

Community
  • 1
  • 1
Khaloymes
  • 759
  • 2
  • 6
  • 9

2 Answers2

5

Two ways I know. First is to just use single quotes to start and end the character string:

> cat( 'Learning "R" is fun!' )
Learning "R" is fun!

Second is to escape the double quotes:

> cat( "Learning \"R\" is fun!" )
Learning "R" is fun!

Note that this works because I use cat, which is intended to output strings to the console. It seems you use print() which shows the object rather than output it

Sacha Epskamp
  • 46,463
  • 20
  • 113
  • 131
  • 3
    When I try to use `cat` while sending text to function, the text is formatted properly (using any of your suggestions), only this time, it outputs `Learning "R" is fun!NULL` instead of `Learning "R" is fun!`. Any idea how to terminate that `NULL` addition? (And even more importantly, any idea where did it come from?) – Khaloymes Nov 19 '12 at 07:43
1

You can try these approaches:

foo <- function(numarg = 5, textarg = "** Default text **" ){ 
    cat(c(textarg, "\n")) 
    val <- (numarg^2) + numarg
    return(val) 
}

foo <- function(numarg = 5, textarg = "** Default text **" ){ 
    print(noquote(textarg)) 
    val <- (numarg^2) + numarg
    return(val) 
}

foo( 4, "Learning R is fun!" )
foo( 4, 'Learning "R" is fun!' )
Tyler Rinker
  • 108,132
  • 65
  • 322
  • 519
  • Thanks! They both work! I've noticed I can use just `cat(textarg, "\n")` instead of formatting the output as an array by using `cat(c(textarg, "\n")`. Which is preferred? – Khaloymes Nov 19 '12 at 07:58