Addition quotations around an R function input?

93 Views Asked by At

How do I add quotations around an input to a function in R?

I would like to have something such as,

function_name (x) { 
paste0("The input you have chosen is", x,)
}

function_name(x = gender)

output: "The variable you have chosen is gender"

I know that I could do it using paste0 if the input was function_name("gender"), but I don't know how to do this if the input doesn't have quotations.

I have tried using paste0 to paste single quotations around the word, but gives errors such as:

Error in paste0("'", x, "'") : object 'Gender' not found.

I have also tried escaping the quotation marks, but the slashes are being read and giving errors as well.

Thanks in advance for any suggestions.

2

There are 2 best solutions below

0
Ricardo Semião On

As pointed by AdroMine, this envolves non-standard evaluation. The link he provided is quite useful.

But to provide an answer, you can do the following:

function_name <- function(x) {
  paste("The input you have chosen is", as.character(rlang::enexpr(x)))
}

function_name(x = gender)
[1] "The input you have chosen is gender"

We are capturing the "word" gender before R tries to evaluate it (i.e., tries to find which value should be associated with gender), and then, we are getting the actual text with as.character()

0
Onyambu On

Just wrap the parameter with substitute function. This enables one to NSE:

function_name <- function (x) { 
  paste0("The input you have chosen is ", substitute(x)) #Note here
}

And now you can run:

function_name(gender) # Without quotes
[1] "The input you have chosen is gender"
function_name("gender") # With quotes
[1] "The input you have chosen is gender"