dplyr::mutate_at() with tidyeval

Hi,

Below is a reprex to illustrate the input, desired output, and a failed attempt; hope to get some enlightenment!

  library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
  library(tibble)
df <-
  tibble::tribble(
    ~a, ~a_b,
    1,   NA,
    2,    4,
    3,    5
  )

# desired output
df %>% 
  mutate(c = if_else(is.na(a_b), 0, a))
#> # A tibble: 3 x 3
#>       a   a_b     c
#>   <dbl> <dbl> <dbl>
#> 1     1    NA     0
#> 2     2     4     2
#> 3     3     5     3

# failed attempt
df %>% 
  mutate_at(vars(a),
            funs(if_else(is.na(!!sym(str_c(., '_b'))), 0, .)))

I would build the quosure outside and use quo_name to get character for pasting. on way to do based on your example (not the cleanest)

library(dplyr)
#> 
#> Attachement du package : 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(tibble)
df <-
  tibble::tribble(
    ~a, ~a_b,
    1,   NA,
    2,    4,
    3,    5
  )

# make a quosure 
quo_a <- quo(a)
# use quo_name to get the name of the variable in a quosure
df %>% 
  mutate(c = if_else(is.na(!!sym(paste0(quo_name(quo_a), '_b'))), 0, !!sym(paste0(quo_name(quo_a)))))
#> # A tibble: 3 x 3
#>       a   a_b     c
#>   <dbl> <dbl> <dbl>
#> 1     1    NA     0
#> 2     2     4     2
#> 3     3     5     3
df %>% 
  mutate_at(vars(!!sym(paste0(quo_name(quo_a), "_b"))), funs(c = if_else(is.na(.), 0, .)))
#> # A tibble: 3 x 3
#>       a   a_b     c
#>   <dbl> <dbl> <dbl>
#> 1     1    NA     0
#> 2     2     4     4
#> 3     3     5     5

Created on 2018-12-30 by the reprex package (v0.2.1)

2 Likes

@cderv, thanks for the early NY present :grinning:

No matter at Github or Rstudio Community, you're one of my heroes!

Appreciate your lessons as always.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.