Home > Software engineering >  Declaring a sym without backticks in rlang
Declaring a sym without backticks in rlang

Time:03-04

I am defining a function like this;

afun <- function(formula,data,level){
    dataname <- rlang::sym(deparse(substitute(data)))
    
    call('somefunction',formula = formula,data = dataname,vec = c(2,3,4),level = level)
}

it returns this when I use these variables;

  afun(Sepal.Width ~ Petal.Length,iris,4)

- somefunction(formula = Sepal.Width ~ Petal.Length, data = iris, 
    vec = c(2, 3, 4), level = 4)

but when I use an extra expression in data argument like this;

  afun(Sepal.Width ~ Petal.Length,na.omit(iris),4)

- somefunction(formula = Sepal.Width ~ Petal.Length, data = `na.omit(iris)`, 
    vec = c(2, 3, 4), level = 4)

it returns with backticks.

What should I do my function to return na.omit(iris) not to `na.omit(iris)` ?

Thanks in advance.

CodePudding user response:

You intend na.omit(iris) to be interpreted as a call, not a single symbol. You already capture the call when you use substitute, but for some reason you convert it into a string by using deparse, then convert that into a single symbol using rlang::sym. The backticks appear because you have told rlang to turn the string into a single symbol, rather than keeping it as a call.

Why not use substitute on its own? It's simple and doesn't require an additional package.

afun <- function(formula, data, level) {
    
    call('somefunction', 
         formula = formula, 
         data    = substitute(data), 
         vec     = c(2, 3, 4),
         level   = level)
} 

afun(Sepal.Width ~ Petal.Length, na.omit(iris), 4)
#> somefunction(formula = Sepal.Width ~ Petal.Length, data = na.omit(iris), 
#>     vec = c(2, 3, 4), level = 4)

CodePudding user response:

We may use enexpr if we want to use rlang

afun <- function(formula,data,level){
    dataname <- rlang::enexpr(data)
    
    call('somefunction',formula = formula,data = dataname,vec = c(2,3,4),level = level)
    
    
    
}

-testing

afun(Sepal.Width ~ Petal.Length,na.omit(iris),4)
somefunction(formula = Sepal.Width ~ Petal.Length, data = na.omit(iris), 
    vec = c(2, 3, 4), level = 4)
  • Related