r - R中的自变量和选择类别
问题描述
我有一个如下的数据集。第一列是 id。第二列有年龄组。
dat1 <- read.table(header=TRUE, text="
ID Age
8645 15-24
6228 35-44
5830 15-24
1844 25-34
")
ID Age
1 8645 15-24
2 6228 35-44
3 5830 15-24
4 1844 25-34
我想根据变量类别将类别转换为二进制变量。有几种选择。correlationfunnel
在这里很容易使用。
library(correlationfunnel)
library(dplyr)
dat1 %>%
select(-ID) %>%
binarize()
`Age__15-24` `Age__25-34` `Age__35-44`
<dbl> <dbl> <dbl>
1 1 0 0
2 0 0 1
3 1 0 0
4 0 1 0
但是,对于选择建模框架,我需要生成一个如下所示的矩阵。其中行根据 的第 2 列中的类别重复dat1
。需要在每行(列AgeInd
)中具有二进制结果的列。
ID AgeInd Age_15_24 Age_25_34 Age_35_44
1 8645 1 1 0 0
2 8645 0 0 1 0
3 8645 0 0 0 1
4 6228 0 1 0 0
5 6228 0 0 1 0
6 6228 1 0 0 1
7 5830 1 1 0 0
8 5830 0 0 1 0
9 5830 0 0 0 1
10 1844 0 1 0 0
11 1844 1 0 1 0
12 1844 0 0 0 1
解决方案
这是一种使用dplyr
and的方法tidyr
:
library(dplyr)
library(tidyr)
dat1 %>%
mutate(AgeInd = 1) %>%
complete(ID, Age, fill = list(AgeInd = 0)) %>%
mutate(col = row_number(), n = 1) %>%
pivot_wider(names_from = Age, values_from = n,
names_prefix = 'Age_', values_fill = list(n = 0)) %>%
select(-col)
# A tibble: 12 x 5
# ID AgeInd `Age_15-24` `Age_25-34` `Age_35-44`
# <int> <dbl> <dbl> <dbl> <dbl>
# 1 1844 0 1 0 0
# 2 1844 1 0 1 0
# 3 1844 0 0 0 1
# 4 5830 1 1 0 0
# 5 5830 0 0 1 0
# 6 5830 0 0 0 1
# 7 6228 0 1 0 0
# 8 6228 0 0 1 0
# 9 6228 1 0 0 1
#10 8645 1 1 0 0
#11 8645 0 0 1 0
#12 8645 0 0 0 1
推荐阅读
- google-bigquery - 通过传输功能将数据从一个项目复制到 BQ 中的另一个项目是否需要成本?
- javascript - 用笑话模拟 setTimeout
- reactjs - 在 redux-toolkit 中处理相同功能的更正确方法是什么?
- json - 进行chainlink API调用时替代request.addStringArray
- javascript - 对象引用和复制
- css - 固定宽度的材质 UI 网格流动宽度
- android - 连接到 Rest API 的 Android 客户端
- java - JAXB 通过多个导入从 XSD 生成 Java
- arm - 如何修复目标和构建机器之间的 GLIBC 版本不匹配?
- web-scraping - 所有的不会用 beautifulsoup 打印