【问题标题】:How could I add column and row percentages to a crosstab in R (like in an excel Pivot Table)?如何将列和行百分比添加到 R 中的交叉表(如在 excel 数据透视表中)?
【发布时间】:2021-11-14 15:36:28
【问题描述】:

我有以下代码:

alldata2019_v2 %>% tabyl(agerange,gender) %>% 
                adorn_totals(c("row","col")) %>% 
                mutate_if(is.numeric, format, big.mark = ",") 

它提供了预期的表格:

agerange Female Male Total
17 or less 5 0 5
18 to 24 41,486 84,444 125,930
25 to 29 239,969 543,021 782,990
30 to 34 245,211 604,262 849,473
35 to 39 120,084 397,880 517,964
40 to 44 63,102 235,768 298,870
45 to 49 38,889 154,196 193,085
50 to 54 36,612 134,244 170,856
55 to 59 36,810 115,891 152,701
60 or more 35,690 130,044 165,734
Total 857,858 2,399,750 3,257,608

问题是我找不到按行和按列添加百分比列的方法。有办法吗?

agerange Female Male Total Female_pct Male_pct Age_pct
17 or less 5 0 5 100% 0% 0%
18 to 24 41,486 84,444 125,930 33% 67% 4%
... ... ... ... ... ... ...

输入数据具有以下结构:

gender usertype agerange
Male Subscriber 30 to 34
Female Subscriber 30 to 34
Female Subscriber 25 to 29
Male Subscriber 25 to 29
Male Subscriber 25 to 29
Female Subscriber 35 to 39

【问题讨论】:

  • 您正在使用哪些软件包? janitor?
  • 我试过了,可惜没用
  • @camille tidyverse,lubridate,看门人,data.table 和 knitr
  • @DanielSossa 您可以查看解决方案中的代码。它对我来说很好用(还展示了一个带有 mtcars 数据的可重复示例)
  • adorn_percentages 的输出需要乘以 100 并粘贴 %,如果您需要按照预期的格式

标签: r crosstab


【解决方案1】:

我们可能会使用

library(dplyr)
library(janitor)
library(stringr)
out %>%
    mutate(across(-1, readr::parse_number)) %>% 
   adorn_percentages() %>%
   select(-agerange) %>% 
   rename_with(~ str_c(., 'pct'), everything()) %>%
   bind_cols(out, .)

可重现的例子

data(mtcars)
mtcars %>% 
   tabyl(am, cyl) %>%
    magrittr::multiply_by(1000) %>%
    adorn_totals(c("row", "col")) %>% 
    mutate(across(where(is.numeric), 
      ~ formattable::comma(., digits = 2, big.mark = ","))) -> out

out %>% 
   adorn_percentages() %>% 
   select(-am, -Total) %>%
   rename_with(~ str_c(., 'pct'), everything()) %>%   
    bind_cols(out, .)
    am         4        6         8     Total 4pct 6pct 8pct
     0  3,000.00 4,000.00 12,000.00 19,000.00 0.16 0.21 0.63
  1000  8,000.00 3,000.00  2,000.00 13,000.00 0.62 0.23 0.15
 Total 11,000.00 7,000.00 14,000.00 32,000.00 0.34 0.22 0.44

【讨论】:

    猜你喜欢
    • 2019-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多