如何使用dplyr通过函数中的评估对象的值进行汇总

时间:2019-06-14 15:29:52

标签: r dplyr

我正在编写一个函数,根据输入列(a或b)的值汇总列(c)。该函数不是按a或b列的值进行汇总,而是按整个列进行汇总。

library("dplyr")

df <- data.frame(a = c("X","X","Y","Y"), b = c("L","M","L","M"), c = 
rnorm(4, 0, 100))

fxn <- function(col) {
  df %>% 
    group_by(!!col) %>%
    summarise(total = sum(c))

}

fxn("a")的哪个返回:

# A tibble: 1 x 2
  `"a"` total
  <chr> <dbl>
1 a     83.85636.

但是我想要它返回的是:

# A tibble: 2 x 2
  `"a"` total
  <chr>   <dbl>
1 "X"     Sum of X values.
1 "Y"     Sum of Y values.

0 个答案:

没有答案