gpt4 book ai didi

r - 将列值转换为它们自己的二进制编码列(虚拟变量)

转载 作者:行者123 更新时间:2023-12-04 09:30:45 24 4
gpt4 key购买 nike

我有许多带有性别、年龄、诊断等列的 CSV 文件。

目前,它们的编码如下:

ID, gender, age, diagnosis
1, male, 42, asthma
1, male, 42, anxiety
2, male, 19, asthma
3, female, 23, diabetes
4, female, 61, diabetes
4, female, 61, copd

目标是将此数据转换为此 目标格式 :

旁注:如果可能,最好将原始列名添加到新列名中,例如“age_42”或“gender_female”。
ID, male, female, 42, 19, 23, 61, asthma, anxiety, diabetes, copd
1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0
2, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0
3, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0
4, 0, 1, 0, 0, 0, 1, 0, 0, 1, 1

我尝试使用 reshape2 的 dcast()函数,但正在得到组合,导致矩阵极其稀疏。这是一个仅包含年龄和性别的简化示例:
data.train  <- dcast(data.raw, formula = id ~ gender + age, fun.aggregate = length)

ID, male19, male23, male42, male61, female19, female23, female42, female61
1, 0, 0, 1, 0, 0, 0, 0, 0
2, 1, 0, 0, 0, 0, 0, 0, 0
3, 0, 0, 0, 0, 0, 1, 0, 0
4, 0, 0, 0, 0, 0, 0, 0, 1

鉴于这是机器学习数据准备中相当常见的任务,我想可能有其他库(我不知道)能够执行这种转换。

最佳答案

您需要一个 melt/dcast此处组合(称为 recast )以将所有列转换为一列并避免组合

library(reshape2)
recast(df, ID ~ value, id.var = 1, fun.aggregate = function(x) (length(x) > 0) + 0L)
# ID 19 23 42 61 anxiety asthma copd diabetes female male
# 1 1 0 0 1 0 1 1 0 0 0 1
# 2 2 1 0 0 0 0 1 0 0 0 1
# 3 3 0 1 0 0 0 0 0 1 1 0
# 4 4 0 0 0 1 0 0 1 1 1 0

根据您的旁注,您可以添加 variable在这里也是为了添加名称
recast(df, ID ~ variable + value, id.var = 1, fun.aggregate = function(x) (length(x) > 0) + 0L)
# ID gender_female gender_male age_19 age_23 age_42 age_61 diagnosis_anxiety diagnosis_asthma diagnosis_copd
# 1 1 0 1 0 0 1 0 1 1 0
# 2 2 0 1 1 0 0 0 0 1 0
# 3 3 1 0 0 1 0 0 0 0 0
# 4 4 1 0 0 0 0 1 0 0 1
# diagnosis_diabetes
# 1 0
# 2 0
# 3 1
# 4 1

关于r - 将列值转换为它们自己的二进制编码列(虚拟变量),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30280692/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com