9

I cannot find in dplyr 0.7 a way to replace the mutate_ function which is going to be deprecated.

The mutate_ function is useful in my use case : I store in a database (string format) many instructions (that can be filtered if needed) and apply these instructions to one or several data frames.

For example :

dplyr::tibble(test = "test@test") %>% 
  dplyr::mutate_(.dots = list("test2" = "substr(test, 1, 5)",
                              "test3" = "substr(test, 5, 5)"))

Is there a way to do this with dplyr 0.7 keeping variables and instructions as character?

MrFlick
  • 195,160
  • 17
  • 277
  • 295
stephLH
  • 131
  • 7
  • The doc `?mutate_` states "dplyr now uses tidy evaluation semantics", referring to the rlang package which has a vignette on "tidy evaluation". Good luck if you go down that road. – Frank Jul 27 '17 at 20:04

2 Answers2

9

To expand a little bit on MrFlick's example, let's assume you have a number of instructions stored as strings, as well as the corresponding names that you want to assign to the resulting computations:

ln <- list( "test2", "test3" )
lf <- list( "substr(test, 1, 5)", "substr(test, 5, 5)" )

Match up names to their instructions and convert everything to quosures:

ll <- setNames( lf, ln ) %>% lapply( rlang::parse_quosure )

As per aosmith's suggestion, the entire list can now be passed to mutate, using the special !!! operator:

tibble( test = "test@test" ) %>% mutate( !!! ll )
# # A tibble: 1 x 3
#        test test2 test3
#       <chr> <chr> <chr>
# 1 test@test test@     @
Artem Sokolov
  • 13,196
  • 4
  • 43
  • 74
5

Here's one alternative

a <- "test2"
b <- "test3"
dplyr::tibble(test = "test@test") %>% 
dplyr::mutate(a := !!rlang::parse_expr("substr(test, 1, 5)"),
  b := !!rlang::parse_expr("substr(test, 5, 5)"))
# # A tibble: 1 x 3
#        test     a     b
#       <chr> <chr> <chr>
# 1 test@test test@     @

We use the := operator to dynamically name parameters with strings, and we parse the expression string for the transformation and unwrap it with !!

MrFlick
  • 195,160
  • 17
  • 277
  • 295
  • 1
    @TylerRinker I updated to `parse_expr()` which isn't deprecated and doesn't require the environment to be specified since we're really not using it. – MrFlick Feb 26 '19 at 15:27