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