Dplyr mutate_each inside the function works, but match () does not find the argument

While trying to solve this problem , I had a problem with mutate_each of dplyr . I wanted to use it inside a function and pass arguments to it. This was successful for funs() , but not for matches() .

Let me show you a simple example when the task is to add some tag values ​​to some variables.

 library(dplyr) mydf <- data.frame(this_var1 = c("a", "b", "c", "d", "e"), this_var2 = c("b", "c", "d", "e", "f"), that_var1 = c("x", "y", "z", "w", "u")) mymutate1 <- function(data, tag) { data %>% mutate_each(funs(paste0(., tag))) } mymutate1(mydf, "_foo") this_var1 this_var2 that_var1 1 a_foo b_foo x_foo 2 b_foo c_foo y_foo 3 c_foo d_foo z_foo 4 d_foo e_foo w_foo 5 e_foo f_foo u_foo 

It works like a charm. However, if I also try to control for which variables the transformation needs to be applied, this will not work.

 mymutate2 <- function(data, tag, m) { data %>% mutate_each(funs(paste0(., tag)), matches(m)) } mymutate2(mydf, "_foo", "this") 

This results in the following error: Error in is.string(match) : object 'm' not found . Why is tag found but m not?

The code itself works as intended:

 mydf %>% mutate_each(funs(paste0(., "_foo")), matches("this")) this_var1 this_var2 that_var1 1 a_foo b_foo x 2 b_foo c_foo y 3 c_foo d_foo z 4 d_foo e_foo w 5 e_foo f_foo u 
+6
source share
1 answer

You will want to use the version of the standard grade (SE) mutate_each - i.e. mutate_each_ :

 mymutate2 <- function(data, tag, m) { data %>% mutate_each_(funs(paste0(., tag)), ~matches(m)) } 

For added clarity, the following is equivalent:

 mymutate3 <- function(data, tag, m) { data %>% mutate_each_(~paste0(., tag), ~matches(m)) } 

And for vignette :

"It’s best to use the formula [ ~ as opposed to quote() or using the strings "" ], because the formula captures both the expression for the evaluation and the environment in which it should be evaluated ... Using anything other than the formula, will not be executed because it does not know which environment to look for. "

+6
source

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


All Articles