r - 如何从数据框分类变量和频率列创建交叉表?
问题描述
我有一个数据框性别(男性和女性)、年龄(儿童和成人)、生存(是和否)和频率。如何创建性别和年龄的交叉表?
sex age survive freq
male child yes 4
male adult yes 0
female child yes 6
female adult yes 3
male child no 1
male adult no 0
female child no 2
female adult no 1
解决方案
我认为您正在寻找使用pivot_wider
from重塑您的数据tidyr
:
library(tidyr)
df %>% pivot_wider(., names_from = age, values_from = freq)
# A tibble: 4 x 4
sex survive child adult
<fct> <fct> <int> <int>
1 male yes 4 0
2 female yes 6 3
3 male no 1 0
4 female no 2 1
或者
library(tidyr)
df %>% pivot_wider(., names_from = c(age, survive), values_from = freq)
# A tibble: 2 x 5
sex child_yes adult_yes child_no adult_no
<fct> <int> <int> <int> <int>
1 male 4 0 1 0
2 female 6 3 2 1
是你要找的吗?如果没有,你能提供预期的结果吗?
数据
df = structure(list(sex = structure(c(2L, 2L, 1L, 1L, 2L, 2L, 1L,
1L), .Label = c("female", "male"), class = "factor"), age = structure(c(2L,
1L, 2L, 1L, 2L, 1L, 2L, 1L), .Label = c("adult", "child"), class = "factor"),
survive = structure(c(2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L), .Label = c("no",
"yes"), class = "factor"), freq = c(4L, 0L, 6L, 3L, 1L, 0L,
2L, 1L)), class = "data.frame", row.names = c(NA, -8L))
推荐阅读
- reactjs - url查询字符串参数更改时是否有反应组件事件?
- html - 如何使表格文本永不换行?
- php - 我想从 mysql php 中检索数据
- .net-core - 使用 Azure AD v2.0 对 .NET 的 Azure 管理库进行身份验证
- ionic-framework - 我在运行我的第一个离子项目时遇到问题
- ios - 在 iOS 中的 firebase 数据库中查询
- elasticsearch - 如何通过 HTTP/REST API 调用在 elasticsearch 中使用数据
- javascript - LinkedIn OAuth:请求授权令牌
- spring - 如何让spring管理匿名类的线程
- ajax - 关闭 mondal 后刷新主视图(单击按钮或外部)