使用mutate_进行标准评估,按组

时间:2016-06-15 14:07:12

标签: r dplyr standard-evaluation

我正在尝试使用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)
}

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

setNames中的错误(列表(interp(quote(n_in_group / sum(n_in_group,na.rm = TRUE)*:   参数“nm”缺失,没有默认值

有什么想法?

1 个答案:

答案 0 :(得分:2)

以下是一些基于@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) 
}