我在starwars个数据集中过滤人类.使用‘性别’和‘皮肤 colored颜色 ’列 在人类数据集中,我希望按如下方式创建交叉表:

enter image description here

我的审判:

# Load the starwars dataset 
library(janitor)
library(dplyr)
library(tibble)
starwars_data <- as_tibble(starwars)

# Subset the humans from the starwars dataset
humans_data <- starwars_data %>%
  filter(species == "Human")

# Create the crosstab
crosstab <- table(humans_data$sex, humans_data$skin_color)

# Add row and column totals
crosstab <- addmargins(crosstab)

# Calculate row percentages
row_percentages <- prop.table(crosstab, margin = 1) * 100

# Combine the crosstab and row percentages
crosstab_with_percentages <- cbind(crosstab, row_percentages)

# Print the result
print(crosstab_with_percentages)

dark fair light none pale tan white Sum     dark     fair     light     none     pale      tan    white
female    0    3     5    1    0   0     0   9 0.000000 16.66667 27.777778 5.555556 0.000000 0.000000 0.000000
male      4   13     5    0    1   2     1  26 7.692308 25.00000  9.615385 0.000000 1.923077 3.846154 1.923077
Sum       4   16    10    1    1   2     1  35 5.714286 22.85714 14.285714 1.428571 1.428571 2.857143 1.428571
       Sum
female  50
male    50
Sum     50

推荐答案

您可以在tidyVerse中将其作为一个普通的数据争论任务来完成:

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

R相关问答推荐

在数据表中呈现数学符号

如何使用`ggplot2::geom_segment()`或`ggspatial::geom_spatial_segment()`来处理不在格林威治中心的sf对象?

如何计算前一行的值,直到达到标准?

使用R中相同值创建分组观测指标

Highcharter多次钻取不起作用,使用不同方法

在不安装软件包的情况下测试更新

根据模式将一列拆分为多列,并在R中进行拆分

如何在R中对深度嵌套的tibbles中的非空连续行求和?

汇总数据表中两个特定列条目的值

如果某些列全部为NA,则更改列

非线性混合效应模型(NLME)预测变量的置信区间

LOF中的插图短文字幕

如何用书面利率绘制geom_bar图

根据纬度和距离连接两个数据集

使用shiny 中的所选要素行下拉菜单

如何在内联代码中添加额外的空格(R Markdown)

从两个数据帧中,有没有办法计算R中一列的唯一值?

使用nls()函数的非线性模型的半正态图

如何修改Rust中的R字符串并将其赋给新的R变量,并使用extendr保留原始R字符串

以列名的字符向量作为参数按行应用自定义函数