您可以将此作为一项琐碎的数据争论任务:
library(tidyverse)
starwars %>%
filter(species == "Human") %>%
with(table(sex, skin_color)) %>%
as.data.frame() %>%
bind_rows(
bind_cols(tibble(sex = "Total"),
summarise(., Freq = sum(Freq), .by = skin_color))) %>%
mutate(prop = Freq/sum(Freq), .by = sex) %>%
mutate(prop = paste0(Freq, " (", scales::percent(prop, 1), ")")) %>%
select(-Freq) %>%
pivot_wider(names_from = skin_color, values_from = prop) %>%
rowwise() %>%
mutate(Sum = sum(sapply(strsplit(c_across(-1), " "),
\(x) as.numeric(x[1])))) %>%
mutate(Sum = paste(Sum, "(100%)")) %>%
rename(`sex / skin_color` = sex) %>%
as.data.frame(check.names = FALSE)
#> sex / skin_color dark fair light pale tan white Sum
#> 1 female 0 (0%) 3 (33%) 6 (67%) 0 (0%) 0 (0%) 0 (0%) 9 (100%)
#> 2 male 4 (15%) 13 (50%) 5 (19%) 1 (4%) 2 (8%) 1 (4%) 26 (100%)
#> 3 Total 4 (11%) 16 (46%) 11 (31%) 1 (3%) 2 (6%) 1 (3%) 35 (100%)
创建于2024-02-01
reprex v2.0.2