How to use quosures within scoped variants after deprecation of funs()

If you wanted to give your argument as a string you could take advantage of the .data pronoun as a work-around to quosures. (Differences in output below has to do with the seed; I used set.seed(16).)

myfun2 <- function(df, weight) {
     summarize_at(df, vars(starts_with("var")), 
                  list(~sum(if_else(. == 1, .data[[weight]], 0))/sum(.data[[weight]]) ) )
}

myfun2(data, "weighting")

# A tibble: 1 x 3
   vara  varb  varc
  <dbl> <dbl> <dbl>
1 0.701 0.609 0.287

I had a hard time turning the symbol into a string with tidyeval functions, which is a problem that looks similar to this question. This is a case where the old deparse()-substitute() approach could be used, but there may be something added to rlang since that post.

myfun3 <- function(df, weight) {
     weight = deparse(substitute(weight))
     summarize_at(df, vars(starts_with("var")), 
                  list(~sum(if_else(. == 1, .data[[weight]], 0))/sum(.data[[weight]])) )
}

myfun3(data, weighting)
# A tibble: 1 x 3
   vara  varb  varc
  <dbl> <dbl> <dbl>
1 0.701 0.609 0.287

Back to add that I really thought rlang::as_label() , er, rlang::as_name() should help for making things strings, but I couldn't figure it out yesterday. :stuck_out_tongue_winking_eye: Turns out it can be used after enquo() to do so, which I was missing.

myfun3 <- function(df, weight) {
     weight = rlang::as_name(enquo(weight))
     summarize_at(df, vars(starts_with("var")), 
                  list(~sum(if_else(. == 1, .data[[weight]], 0))/sum(.data[[weight]])) )
}
3 Likes