Send a text string containing double quotes to function

double-quotes, output, r, string-formatting

Solution

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!' )

Problem

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.

Original source

Related problems