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'))
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With