首页 > 解决方案 > 在双向频率表中同时显示 Ns 和比例

问题描述

我正在尝试创建一个不符合“整洁”输出的发布表:

dummy <- data.frame(categorical_1 = c("a", "b", "a", "a", "b", "b", "a", "b", "b", "a"),
                    categorical_2 = c(rep("one", 5), rep("two", 5)),
                    numeric = sample(1:10, 10))

dummy %>%
  count(categorical_1, categorical_2) %>%
  group_by(categorical_1) %>%      
  mutate(prop = prop.table(n))

Tidyverse 输出

  categorical_1 categorical_2     n  prop
  <fct>         <fct>         <int> <dbl>
1 a             one               3   0.6
2 a             two               2   0.4
3 b             one               2   0.4
4 b             two               3   0.6

期望的输出:

Category          One       Two
a                 3 (0.6)     2 (0.4)
b                 2 (0.4)     3 (0.6)

也许我可以应用其他mutate步骤来使表格符合我想要的输出?

标签: rdplyr

解决方案


library(janitor)

dummy %>%
  tabyl(categorical_1, categorical_2) %>%
  adorn_percentages("row") %>%
  adorn_ns(position = "front")

#>  categorical_1     one     two
#>              a 3 (0.6) 2 (0.4)
#>              b 2 (0.4) 3 (0.6)

推荐阅读