创建“交叉表”。样式输出 [英] Creating a "crosstabs" style output

查看:92
本文介绍了创建“交叉表”。样式输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个样本数据集:

id <- 1:100
gender <- sample(c('M','F'), 100, replace=TRUE)
age <- sample(18:22, 100, replace=TRUE)
ethnicity <- sample(c('W','B','H','A','O'), 100, replace = TRUE)
grade <- sample(LETTERS[1:4], 100, replace=TRUE)

df <- cbind(id,gender,age,ethnicity,grade) %>% as.data.frame()

我要实现的输出是这样的:

My output I'm trying to achieve is as such:

+-------------+-------+----+----+----+----+
| Column Name | Value | A  | B  | C  | D  |
+-------------+-------+----+----+----+----+
| Gender      | F     | 15 | 11 | 17 | 10 |
| Gender      | M     |  9 | 17 | 14 |  7 |
| Age         | 18    |  4 |  6 |  5 |  4 |
| Age         | 19    |  3 |  6 |  4 |  3 |
| Age         | 20    |  5 |  6 |  7 |  3 |
| Age         | 21    |  7 |  7 |  5 |  4 |
| Age         | 22    |  5 |  3 | 10 |  3 |
| Ethnicity   | A     |  1 |  9 |  9 |  6 |
| Ethnicity   | B     |  7 |  8 |  5 |  2 |
| Ethnicity   | H     |  4 |  4 |  5 |  2 |
| Ethnicity   | O     |  6 |  4 |  5 |  4 |
| Ethnicity   | W     |  6 |  3 |  7 |  3 |
+-------------+-------+----+----+----+----+

因此,我尝试创建一行,将三类变量(例如: 22岁的西班牙裔女性有2个A,0个B,2个C等...,我只是希望按性别,年龄和种族划分的年级分布将其分解,但它们都合而为一

So I'm not trying to create a row that say, combines the three categorical variables (Ex: "Hispanic Females Age 22 got 2 A's, 0 B's, 2 C's, etc..." I just want it broken out by the grade distribution by each gender, age, and ethnicity, but they're all in one column.

什么是最好的方法?

推荐答案

使用 dplyr tidyr ,我们可以获取长格式的数据,计数的每个出现$ c>,并以宽格式获取数据。

Using dplyr and tidyr we can get the data in long format, count occurrences of each value for each grade and get the data back in wide format.

library(dplyr)
library(tidyr)

df %>%
 select(-id) %>%
 pivot_longer(cols = -grade) %>%
 count(value, grade) %>%
 pivot_wider(names_from = grade, values_from = n)


# A tibble: 12 x 5
#   value     A     B     C     D
#   <fct> <int> <int> <int> <int>
# 1 F         8    10    12    13
# 2 M        13    18    11    15
# 3 18        2     4     7     6
# 4 19        5     6     4     4
# 5 20        3     6     3     8
# 6 21        6     5     5     3
# 7 22        5     7     4     7
# 8 A         5     3     1     5
# 9 B         5     5     6     7
#10 H         1     4     3     3
#11 O         3    10     7     7
#12 W         7     6     6     6

数据

set.seed(123)
id <- 1:100
gender <- sample(c('M','F'), 100, replace=TRUE)
age <- sample(18:22, 100, replace=TRUE)
ethnicity <- sample(c('W','B','H','A','O'), 100, replace = TRUE)
grade <- sample(LETTERS[1:4], 100, replace=TRUE)
df <- cbind(id,gender,age,ethnicity,grade) %>% as.data.frame()

这篇关于创建“交叉表”。样式输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆