【问题标题】:Issue in Group_by_at & Group_byGroup_by_at 和 Group_by 中的问题
【发布时间】:2019-10-21 15:04:07
【问题描述】:

下面是我要执行的数据框和代码。 如下所示,我想通过xcolor 进行分组。 x 是一个字符串,因此我使用了 group_by_at 函数。

df <- data.frame(
        color = c("Yellow", "Blue", "Green", "Red", "Magenta"),
        values = c(24, 24, 34, 45, 49),
        Quarter = c("Period1","Period2" , "Period3", "Period3", "Period1"),
        Market = c("Camden", "StreetA", "DansFireplace", "StreetA", "DansFireplace"))
    
list = c("Market", "Quarter")

df_all <- do.call(rbind, lapply(list, function(x) {
    df_l <- df %>% 
              group_by_at(x) %>% 
              group_by(color) %>%
              summarise(values = sum(values)) %>% 
              mutate(cut = x) %>% 
              data.frame()
    colnames(df_l)[colnames(df_l) == x] <- "Grouping"
    df_l
}))

问题在于,当此代码运行时,它没有按x 分组。只有当我删除group_by(color) 时,它才会按x 分组。

我的目标是同时按xcolor 分组。

【问题讨论】:

  • @joran 没试过,不行。

标签: r dplyr plyr


【解决方案1】:

如果我正确理解您的问题,请在同一 group_by 语句中包含 colorx

df_all <- do.call(rbind, lapply(list, function(x){
  df_l= df %>% group_by_at(c(x, "color")) %>% 
    summarise(values = sum(values)) %>% 
    mutate(cut= x) %>% 
    data.frame()
  colnames(df_l)[colnames(df_l)==x] <- "Grouping"
  df_l
}))

这给出了:

        Grouping   color values     cut
1         Camden  Yellow     24  Market
2  DansFireplace   Green     34  Market
3  DansFireplace Magenta     49  Market
4        StreetA    Blue     24  Market
5        StreetA     Red     45  Market
6        Period1 Magenta     49 Quarter
7        Period1  Yellow     24 Quarter
8        Period2    Blue     24 Quarter
9        Period3   Green     34 Quarter
10       Period3     Red     45 Quarter

【讨论】:

    猜你喜欢
    • 2023-03-11
    • 2023-01-19
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 2015-09-13
    • 2015-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多