【问题标题】:Flip group_by variable to columns, and flip columns to rows dplyr将 group_by 变量翻转为列,并将列翻转为行 dplyr
【发布时间】:2020-04-06 21:53:19
【问题描述】:

提前感谢您的回复!我在 Rstudio 工作,试图创建我的客户正在寻找的特定表格格式。具体来说,我想将每个指标显示为一行,并将 group_by 变量(在本例中为应用程序类型)显示为一列。我正在使用 group_by 按应用程序类型整合我的所有数据,并且我正在使用 summarise 函数来创建新变量。

subs <- data.frame(
  App_type = c('A','A','A','B','B','B','C','C','C','C'), 
  Has_error = c(1,1,1,0,0,1,1,0,1,1), 
  Has_critical_error = c(1,0,1,0,0,1,0,0,1,1)
)

我可以按应用程序类型将提交的内容分组在一起,以查看包含错误的提交总数和包含严重错误的总数。这就是我所做的 -

subs %>% 
group_by(App_type) %>% 
summarise(
  total_sub = n(), 
  total_error = sum(Has_error), 
  total_critical_error = sum(Has_critical_error)
)
# A tibble: 3 x 4
  App_type total_sub total_error total_critical_error
  <fct>        <int>       <dbl>                <dbl>
1 A                3           3                    2
2 B                3           1                    1
3 C                4           3                    2

但是,我的客户希望以这种方式查看应用程序总数。


                          A          B           C           TOTAL
1 total_sub               3          3           4           10
2 total_error             3          1           3           7
3 total_critical_error    2          1           2           5

【问题讨论】:

    标签: r dplyr format


    【解决方案1】:

    我们可以在整形为“long”后转为“wide”格式,然后将列名“name”更改为rowname

    library(dplyr)
    library(tidyr)
    library(tibble)
    subs %>% 
      group_by(App_type) %>% 
      summarise(
         total_sub = n(), 
         total_error = sum(Has_error), 
         total_critical_error = sum(Has_critical_error))     %>% 
      pivot_longer(cols = -App_type) %>% 
      pivot_wider(names_from = App_type, values_from = value) %>%
      mutate(TOTAL =  A + B + C) %>%
      column_to_rownames("name")
    #                      A B C TOTAL
    #total_sub            3 3 4    10
    #total_error          3 1 3     7
    #total_critical_error 2 1 2     5
    

    或者另一个选项是transpose from data.table

    library(data.table)
    data.table::transpose(setDT(out), make.names = 'App_type',
          keep.names = 'name')[, TOTAL := A + B + C][]
    

    out 是 OP 的汇总输出

    out <- subs %>% 
            group_by(App_type) %>% 
            summarise(
              total_sub = n(), 
              total_error = sum(Has_error), 
              total_critical_error = sum(Has_critical_error)
              )
    

    或者base R

    addmargins(t(cbind(total_sub = as.integer(table(subs$App_type)),
          rowsum(subs[-1], subs$App_type))), 2)
    #                   A B C Sum
    #total_sub          3 3 4  10
    #Has_error          3 1 3   7
    #Has_critical_error 2 1 2   5
    

    【讨论】:

    • 非常感谢!这正是我所需要的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-07
    相关资源
    最近更新 更多