代码之家  ›  专栏  ›  技术社区  ›  PaulS

单次调用pivot_的顺序聚合

  •  0
  • PaulS  · 技术社区  · 4 年前

    考虑数据文件:

    df <- data.frame(x = c(1,2,1,1), y = c("a", "a", "b", "a"))
    

    library(tidyverse)
    
    df %>% 
      pivot_wider(x, names_from = y, values_from = y, values_fn = length, names_prefix = "tot_", values_fill = 0) %>% 
      mutate(per_a = 100*tot_a / rowSums(select(.,starts_with("tot_")))) %>% 
      mutate(per_b = 100*tot_b / rowSums(select(.,starts_with("tot_"))))
    

    一个人得到结果

       <dbl> <int> <int> <dbl> <dbl>
     1     1     2     1  66.7  33.3
     2     2     1     0 100     0
    

    我的问题是:是否有可能使用 召唤 pivot_wider mutate ?

    1 回复  |  直到 4 年前
        1
  •  1
  •   thelatemail    4 年前

    你需要 group_by 我想如果你想做这件事 pivot_wider mutate -每一个 per 百分比列分别显示。

    df %>%
      group_by(x,y) %>%
      count(name="tot") %>%
      group_by(x) %>%
      mutate(per = tot / sum(tot)) %>%
      pivot_wider(id_cols = x, names_from=y, values_from=c(tot,per))
    
    ## A tibble: 2 x 5
    ## Groups:   x [2]
    #      x tot_a tot_b per_a  per_b
    #  <dbl> <int> <int> <dbl>  <dbl>
    #1     1     2     1 0.667  0.333
    #2     2     1    NA 1     NA   
    

    这对我来说是“整洁”的,因为您正在以长格式、整洁的数据在2个分组扫描中进行所有计算,而不是试图手动选择宽格式的多个列。