standard evaluation in dplyr: summarise a variable given as a character string

Please note that this answer does not apply to dplyr >= 0.7.0, but to previous versions.

[dplyr 0.7.0] has a new approach to non-standard evaluation (NSE) called tidyeval. It is described in detail in vignette("programming").


The dplyr vignette on non-standard evalutation is helpful here. Check the section “Mixing constants and variables” and you find that the function interp from package lazyeval could be used, and “[u]se as.name if you have a character string that gives a variable name”:

library(lazyeval)
df %>%
  select(-matches(drp)) %>%
  group_by_(key) %>%
  summarise_(sum_val = interp(~sum(var, na.rm = TRUE), var = as.name(val)))
#   v3 sum_val
# 1  A      21
# 2  B      19

Leave a Comment