Home > Back-end >  Passing column name as argument in function within pipes
Passing column name as argument in function within pipes

Time:11-27

I'm trying to write a function by passing a variable name as an argument. This is then used in a downstream pipe to mutate a variable.

Using a more classic but perhaps a little bit clunky approach I am able to do this:

var = "Sepal.Width"

scale_fun1 = function(dat,var) {
  
  dat[,"new_var"] = dat[,var]*100
  
  return(dat)
  
}

scale_fun1(iris,var)

I thought this would be straightforward using a pipe but it's proving more difficult then I thought as when the function passes the pipe var it doesn't parse as it should which results in a non-numeric argument to binary operator error. How can this be fixed please?

var = "Sepal.Width"

scale_fun2 = function(dat,var) {
  
  iris %>% dplyr::mutate(new_variable = var * 100)
  
}

scale_fun2(iris,var)

CodePudding user response:

You need to make use of non standard evaluation which is worth a quick read about. In this case you most likely need to !! infront of var in the mutate line.

Here's the line:

mutate(new_variable = !!sym(var) * 100)
  • Related