r - standard evaluation in dplyr: summarise_ on variable given as a character string -
r - standard evaluation in dplyr: summarise_ on variable given as a character string -
i want refer unknown column name within summarise. standard evaluation functions introduced in dplyr 0.3 allow column names referenced using variables, doesn't appear work when phone call base r function within e.g. summarise.
library(dplyr) key <- "v3" val <- "v2" drp <- "v1" df <- data_frame(v1 = 1:5, v2 = 6:10, v3 = c(rep("a", 3), rep("b", 2))) the df looks this:
> df source: local info frame [5 x 3] v1 v2 v3 1 1 6 2 2 7 3 3 8 4 4 9 b 5 5 10 b i want drop v1, grouping v3, , sum v2 each group:
df %>% select(-matches(drp)) %>% group_by_(key) %>% summarise_(sum(val, na.rm = true)) error in sum(val, na.rm = true) : invalid 'type' (character) of argument the nse version of select() works fine, since can match character string. se version of group_by() works fine, since can take variables arguments , evaluate them. however, haven't found way accomplish similar results when using base of operations r functions within dplyr functions.
things don't work:
df %>% group_by_(key) %>% summarise_(sum(get(val), na.rm = true)) error in get(val) : object 'v2' not found df %>% group_by_(key) %>% summarise_(sum(eval(as.symbol(val)), na.rm = true)) error in eval(expr, envir, enclos) : object 'v2' not found i've checked out several related questions, none of proposed solutions have worked me far.
the dplyr vignette on non-standard evalutation helpful here. check section "mixing constants , variables" , find function interp bundle lazyeval used, , "[u]se as.name if have character string gives 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 21 # 2 b 19 r dplyr
Comments
Post a Comment