我正在尝试为发布创建不符合“整洁”输出的表:
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))
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_wider
合并后n
并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))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句