使用 mutate_ 进行标准评估以按组计算百分比

Standard evaluation with mutate_ to calculate percentages by group

我正在尝试使用 dplyr 的标准评估来计算作为两个分组变量函数的百分比。问题出在我的mutate_ statement

这是一个数据集:

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")

这是我正在使用的代码:

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)
}

当我 运行 代码时,我收到一个错误:

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

有什么想法吗?

下面是一些基于@Frank 回复的代码:

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) 
}