r - dplyr standard evaluation: summarise_ with variable name for summed variable -
i went through lot of questions similar mine addressed 1 part of problem. using dplyr standard evaluation accommodate variable names. works fine filter_ , group_by_ in pipe. however, summarize cannot have variable name metric i'm summing. example make clear.
library(dplyr) library(lazyeval) # create data <- data.frame( x = c(2010, 2010, 2011, 2011, 2011), y_zm = c(rep(10, 5)), y_r2 = c(rep(20, 5))) # define variable names tag <- "2011" metric <- "y" run1 <- "zm" run2 <- "r2" # working example pipe fixed variable name %>% filter_(~x == tag) %>% group_by_(tag) %>% summarise_(variable_name = interp(~sum(var, na.rm = t), var = as.name(paste0(metric,"_",run1)))) # non-working example of want %>% filter_(~x == tag) %>% group_by_(tag) %>% summarise_(as.name(paste0(metric,"_",run1)) = interp(~sum(var, na.rm = t), var = as.name(paste0(metric,"_",run1))))
i tried lot of different things involving as.name() or interp() nothing seems work.
after poring on nse vignette awhile , poking @ things, found can use setnames
within summarise_
if use .dots
argument , put interp
work in list.
a %>% filter_(~x == tag) %>% group_by_(tag) %>% summarise_(.dots = setnames(list(interp(~sum(var, na.rm = true), var = as.name(paste0(metric,"_",run1)))), paste0(metric,"_",run1))) source: local data frame [1 x 2] 2011 y_zm 1 2011 30
you add rename_
step same thing. see being less ideal, relies on knowing name used in summarise_
. if use same name, variable_name
, seem viable alternative situations.
a %>% filter_(~x == tag) %>% group_by_(tag) %>% summarise_(variable_name = interp(~sum(var, na.rm = t), var = as.name(paste0(metric,"_",run1)))) %>% rename_(.dots = setnames("variable_name", paste0(metric,"_",run1))) source: local data frame [1 x 2] 2011 y_zm 1 2011 30
Comments
Post a Comment