【发布时间】:2015-07-28 15:05:37
【问题描述】:
我有许多包含性别、年龄、诊断等列的 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
鉴于这是机器学习数据准备中相当常见的任务,我想可能还有其他库(我不知道)能够执行此转换。
【问题讨论】:
标签: r sparse-matrix reshape2