Dplyr mutate, user-defined function and variable name as characters

I still don’t quite understand how I can pass certain dplyr expressions.

I would like to use a user-defined function in the mutate and be able to pass column names as characters. I tried several things with interp {lazyeval} without success.

See an example of a dummy example.

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')) 
+5
source share
1 answer

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")) ) 

OP Method

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

Update

In the devel dplyr version ( 0.6.0 will be released soon in April 2017), it can also be with quosure

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

quos are quoted and inside mutate we use !!! to unquote a list for rating

 identical(res2, res3) #[1] TRUE 
+5
source

Source: https://habr.com/ru/post/1244203/


All Articles