Search code examples
rfunctiontextcharacterquotes

How to take in text/character argument without quotes


Sorry if the question is unclear. Feel free to change it.

So basically I am trying to find a way so that text/character string arguments for a function don't require quotes.

foo  = function(x, y, data){
    n1 = length(data[,x])
    n2 = length(data[,y])
    cat(n1, n1)
 }

If I use the following code

data(survey)
foo(Sex, Fold, survey)

I will get an error message. But if I use the following:

foo("Sex", "Fold", survey)

or

foo(1, 5, survey)

the function will give me what I want. So I wonder if there is any way to construct the function such that I won't need to use quotes around the column names. Thanks!


Solution

  • Well, this will work with the symbols:

    foo  = function(x,y, data){
        n1 <- length(eval(substitute(x),data))
        n2 <- length(eval(substitute(y),data))
        cat(n1,n2)  
    }
    

    If you wanted this to work with quoted variable names and integer indices as well, you could simply check x and y at the start with some simple if-else branching.

    But it comes with the standard warning that the eval(substitute()) idiom can be dangerous to use. (You may not always be able to anticipate how it won't work in some cases, and you may not realize when it isn't working.)