Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dplyr mutate, custom function and variable name as characters

Tags:

r

dplyr

It's still not fully clear to me how I can pass certain expressions to dplyr.

I'd like to use a user defined function within mutate and be able to pass it column names as characters. I tried a few things with interp{lazyeval} with no success.

See the dummy example below.

library(dplyr)
library(lazyeval)

# Define custom function
sumVar <- function(x, y) { x + y }

# Using bare column names (OK)
iris %>%
  mutate(newVar = sumVar(Petal.Length, Petal.Width))

# Using characters for column names (does not work)
iris %>%
  mutate_(newVar = sumVar('Petal.Length', 'Petal.Width'))
like image 608
Loïc Dutrieux Avatar asked Mar 01 '16 10:03

Loïc Dutrieux


1 Answers

We can try

library(lazyeval)
library(dplyr)
res1 <- iris %>% 
           mutate_(newVar= interp(~sumVar(x, y),
                x= as.name("Petal.Length"), 
                y = as.name("Petal.Width")) )

The OP's method

res2 <- iris %>%
          mutate(newVar = sumVar(Petal.Length, Petal.Width))
identical(res1, res2)
#[1] TRUE

Update

In the devel version of dplyr (soon to be released 0.6.0 in April 2017), this can be also with quosure

varNames <- quos(Petal.Length,  Petal.Width)
res3 <- iris %>%
            mutate(newVar = sumVar(!!! varNames))

The quos are quoting and inside the mutate, we use !!! to unquote a list for evaluation

identical(res2, res3)
#[1] TRUE
like image 114
akrun Avatar answered Sep 23 '22 21:09

akrun