1
votes

I am struggling for programming with dplyr with mutate.

Below a reproducible example.

library(tidyverse)
test <- tibble(a=1:10, b=1:10)

mute_function <- function(var, table) {

  quo_var <- enquo(var)

  sub_tb <-
    table %>%
    dplyr::select(!!quo_var, b) %>%
    mutate(new_var=!!quo_var)

  return(sub_tb)
}

When applying the function

mute_function(var = "a", table = test)

I get :

# A tibble: 10 x 3
       a     b new_var
   <int> <int> <chr>  
 1     1     1 a      
 2     2     2 a      
 3     3     3 a      
 4     4     4 a      
 5     5     5 a      
 6     6     6 a      
 7     7     7 a      
 8     8     8 a      
 9     9     9 a      
10    10    10 a  

I want to get a new variable combining values from a and others variables. In the case above, I was expecting new_var identical to a.

Obviously, the following does not work:

mute_function <- function(var, table) {

  quo_var <- enquo(var)

  sub_tb <-
    table %>%
    dplyr::select(!!quo_var, b) %>%
    mutate(new_var=!!quo_var/b)

  return(sub_tb)
}

 mute_function(var = "a", table = test)

I don't understand why altought I have been reading carefully dplyr vignette for programming.

Thanks in advance for help

1

1 Answers

3
votes

If we are passing a character string, use sym to convert to symbol instead of a quosure

mute_function <- function(var, table) {

  quo_var <- rlang::sym(var)

  sub_tb <-
    table %>%
    dplyr::select(!!quo_var, b) %>%
    mutate(new_var=!!quo_var/b)

  return(sub_tb)
}

out <- mute_function(var = "a", table = test)
out
# A tibble: 10 x 3
#       a     b new_var
#   <int> <int>   <dbl>
# 1     1     1       1
# 2     2     2       1
# 3     3     3       1
# 4     4     4       1
# 5     5     5       1
# 6     6     6       1
# 7     7     7       1
# 8     8     8       1
# 9     9     9       1
#10    10    10       1

But, if the objective is to pass arguments, unquoted, the OP's function should work correctly

mute_function(var = a, table = test)

However, we can pass both quoted and unquoted strings with

mute_function <- function(var, table) {

  quo_var <- rlang::parse_expr(quo_name(enquo(var)))

  sub_tb <-
    table %>%
    dplyr::select(!!quo_var, b) %>%
    mutate(new_var=!!quo_var/b)

  return(sub_tb)
}

out1 <- mute_function(var = "a", table = test)
out2 <- mute_function(var = a, table = test)
identical(out1, out2)
#[1] TRUE
identical(out, out1)
#[1] TRUE