Search code examples
rnaming

Convert string to non-string input for function


How can I store a string (e.g., the column range "cyl:drat, vs:gear") so that I can use it in a function where it should not be interpreted as character string?


For example, I would like to execute the following command:

subset(mtcars, select=c(disp:drat, vs:gear))   

But assign the content for select to a variable x:

x <- as.name("cyl:drat, vs:gear")
subset(mtcars, select=x)
#Error in x[j] : invalid subscript type 'symbol'

library(rlang)
x <- quo(!! sym("cyl:drat, vs:gear"))
subset(mtcars, select=x)
#Error in x[j] : invalid subscript type 'language'

x <- parse_expr("cyl:drat, vs:gear")
subset(mtcars, select=x)
#Error in x[j] : invalid subscript type 'language'

Assigning x <-"cyl" works, but x <-"cyl:drat" similarly fails.


Hints as to what format x should have would already be a welcome start.


Solution

  • You missed the c() in your expression, and you also need to eval your expressions inside subset:

    library(rlang)
    
    x <- parse_expr("c(cyl:drat, vs:gear)")
    subset(mtcars, select=eval(x))
    

    parse_expr is equivalent to parse in base R:

    x2 = parse(text="c(cyl:drat, vs:gear)")
    subset(mtcars, select=eval(x2))
    

    You can also use parse_expr or parse_exprs alongside select from dplyr, which is where it was intended to be used:

    library(dplyr)
    
    select(mtcars, !! x)
    

    or for splicing a list of expressions:

    y = parse_exprs("cyl:drat; vs:gear")
    select(mtcars, !!! y)