在双向频率表中同时显示Ns和比例

在双向频率表中同时显示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步骤可以应用,以使表格符合所需的输出?

最佳答案

pivot_widern合并为一列后,即可使用prop

library(tidyverse)

d2 %>%
  mutate(v = paste0(n, ' (', prop, ')')) %>%
  pivot_wider(id_cols = categorical_1, names_from = categorical_2, values_from = v) %>%
  rename_at(1, ~'Category')

# # A tibble: 2 x 3
# # Groups:   Category [2]
#   Category one     two
#   <fct>    <chr>   <chr>
# 1 a        3 (0.6) 2 (0.4)
# 2 b        2 (0.4) 3 (0.6)

问题的初始数据
d2 <-
  dummy %>%
    count(categorical_1, categorical_2) %>%
    group_by(categorical_1) %>%
    mutate(prop = prop.table(n))

关于r - 在双向频率表中同时显示Ns和比例,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58752105/

10-12 19:11