r - summarise_at 对不同的变量使用不同的函数

标签 r dplyr tidyverse

当我在dplyr中使用group_by和summary时,自然可以对不同的变量应用不同的summary函数。例如:

    library(tidyverse)

    df <- tribble(
      ~category,   ~x,  ~y,  ~z,
      #----------------------
          'a',      4,   6,   8,
          'a',      7,   3,   0,
          'a',      7,   9,   0,
          'b',      2,   8,   8,
          'b',      5,   1,   8,
          'b',      8,   0,   1,
          'c',      2,   1,   1,
          'c',      3,   8,   0,
          'c',      1,   9,   1
     )

    df %>% group_by(category) %>% summarize(
      x=mean(x),
      y=median(y),
      z=first(z)
    )

结果输出:
    # A tibble: 3 x 4
      category     x     y     z
         <chr> <dbl> <dbl> <dbl>
    1        a     6     6     8
    2        b     5     1     8
    3        c     2     8     1

我的问题是,我将如何使用 summarise_at 做到这一点?显然,对于这个例子,这是不必要的,但假设我有很多要取平均值的变量,很多中位数等。

一旦我转向 summarise_at,我会失去这个功能吗?我是否必须对所有变量组使用所有函数,然后扔掉我不想要的函数?

也许我只是遗漏了一些东西,但我无法弄清楚,而且我在文档中没有看到任何这样的例子。任何帮助表示赞赏。

最佳答案

这是一个想法。

library(tidyverse)

df_mean <- df %>%
  group_by(category) %>%
  summarize_at(vars(x), funs(mean(.)))

df_median <- df %>%
  group_by(category) %>%
  summarize_at(vars(y), funs(median(.)))

df_first <- df %>%
  group_by(category) %>%
  summarize_at(vars(z), funs(first(.)))

df_summary <- reduce(list(df_mean, df_median, df_first), 
                     left_join, by = "category")

就像你说的,没有必要使用summarise_at对于这个例子。但是,如果您有很多列需​​要按不同的功能进行汇总,则此策略可能会奏效。您需要在 vars(...) 中指定列每个summarize_at .规则同dplyr::select功能。

更新

这是另一个想法。定义一个函数来修改 summarise_at函数,然后使用 map2使用显示变量和要应用的关联函数的查找列表来应用此函数。在这个例子中,我申请了 meanxy列和 medianz .
# Define a function
summarise_at_fun <- function(variable, func, data){
  data2 <- data %>%
    summarise_at(vars(variable), funs(get(func)(.)))
  return(data2)
}

# Group the data
df2 <- df %>% group_by(category)

# Create a look-up list with function names and variable to apply
look_list <- list(mean = c("x", "y"),
                  median = "z")

# Apply the summarise_at_fun
map2(look_list, names(look_list), summarise_at_fun, data = df2) %>%
  reduce(left_join, by = "category")

# A tibble: 3 x 4
  category     x     y     z
     <chr> <dbl> <dbl> <dbl>
1        a     6     6     0
2        b     5     3     8
3        c     2     6     1

关于r - summarise_at 对不同的变量使用不同的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46188208/

相关文章:

r - 重叠向量,使用值作为输出列表名称

r - 从 R 中的汇总表中排除任意变量

r - qplot 因数条件

r - 在名为 "."的变量上使用 dplyr 函数

r - 如何根据一天中的时间从一个数据帧中派生出 2 个数据帧?

r - 使用 R/tidyverse 将数据框的一列分隔为未定义的列数

r - 从 session 到每分钟总结

r - 查找数据框对角线上的所有零

r - 当列名包含空格时 dplyr::mutate_if 失败

r - dplyr ifelse 语句中的嵌套条件