using = inside bquote inside dplyr function calls

145 views Asked by At
a <- "A"
bquote(tibble::tibble(a = 1:10) %>% dplyr::mutate(`=`(.(as.name(a)), a*2))) %>% eval()
# A tibble: 10 x 2
       a `A = a * 2`
   <int>       <dbl>
 1     1           2
 2     2           4
 3     3           6
 4     4           8
 5     5          10
 6     6          12
 7     7          14
 8     8          16
 9     9          18
10    10          20

Obviously, the column name is not right. It should be A.

But if I do this:

a <- "A"
bquote(tibble::tibble(a = 1:10) %>% dplyr::mutate(.(as.name(a)) = a*2)) %>% eval()
Error: unexpected '=' in "bquote(tibble::tibble(a = 1:10) %>% dplyr::mutate(.(as.name(a)) ="
1

There are 1 answers

0
MrFlick On

The tidyverse tools have their own way of meta programming that doesn't involve bquote and eval(). Instead you would do

tibble::tibble(!!a := 1:10) %>% dplyr::mutate(!!a := .data[[a]]*2)

The := let's you assign parameter names dynamically. For more info check out vignette("programming", "dplyr")