Standard evaluation with mutate_ to calculate percentages by group

73 views Asked by At

I am trying to use standard evaluation with dplyr to calculate percents as a function of two grouping variables. The problem is in my mutate_ statement.

Here is a dataset:

structure(list(
    var1 = structure(c(2L, 1L, 1L, 2L, 1L, 2L, 1L, 
    2L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 2L, 1L, 1L, 
    2L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 2L, 1L, 2L, 
    2L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 
    2L, 2L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 1L, 
    1L, 2L, 2L, 1L, 2L, 1L, 1L, 2L, 2L, 2L, 1L, 1L, 1L, 2L, 1L, 1L, 
    2L, 2L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 1L, 1L
    ), 
    .Label = c("No", "Yes"), class = "factor"), 
    var2 = structure(c(2L, 2L, 1L, 2L, 
    2L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 1L, 2L, 2L, 1L, 1L, 2L, 1L, 2L, 
    1L, 2L, 2L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 1L, 
    1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 
    2L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 2L, 1L, 2L, 2L, 1L, 1L, 1L, 
    2L, 1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 2L, 1L, 2L, 1L, 
    1L, 1L, 2L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 2L, 2L, 2L
    ), 
    .Label = c("Female", "Male"), class = "factor")), 
    .Names = c("var1", "var2"), row.names = c(NA, -100L), class = "data.frame")

Here is the code I am working with:

for_plots = function(data, var1, var2){
  grouped_data = data %>% group_by_(var1, var2) %>% 
  summarise_(n_in_group = ~n()) %>% 
  mutate_(.dots = setNames(list(
    interp(quote(n_in_group / sum(n_in_group, na.rm = TRUE) * 100),
           n_in_group = as.name(n_in_group)))
    ))
  return(grouped_data)
}

When I run the code, I receive an error:

Error in setNames(list(interp(quote(n_in_group/sum(n_in_group, na.rm = TRUE) * : argument "nm" is missing, with no default

Any thoughts?

1

There are 1 answers

0
Chris On BEST ANSWER

Here is some code based on @Frank's response:

for_plots = function(data, var1, var2) { 
   grouped_data = data %>% group_by_(var1, var2) %>% 
     summarise_(n_in_group = ~n()) %>% 
     mutate(percent = (n_in_group / sum(n_in_group, na.rm = TRUE)) * 100) 
   return(grouped_data) 
}