【发布时间】:2014-09-11 18:11:13
【问题描述】:
我有一个包含 12901 个 categorical 和 NA 观察值的数据集,包含 34 个变量。我将使用该数据集通过对消费者人口统计数据进行聚类来创建市场细分研究。
对于categorical 变量,我想转换为numeric 二进制数据。例如,变量HouseholdIncome 有六个类别:50K-75k、75k-100k、35k-50k、100k-125k、150k-175k 和 Other。我希望将HouseholdIncome 分解为六个变量 (0,0,0,0,0,1), (0,0,0,0,1,0), (0,0,0,1,0 ,0)、(0,0,1,0,0,0)、(0,1,0,0,0,0) 和 (1,0,0,0,0,0)。
问题:如何将分类值更改为二进制变量,同时保留NAs?
我的机器:
> sessionInfo()
R version 3.1.0 (2014-04-10)
Platform: x86_64-apple-darwin13.1.0 (64-bit)
我的数据:
#Head of first six rows of the first six columns
> head(Store4df)
Age Gender HouseholdIncome MaritalStatus PresenceofChildren HomeOwnerStatus
1 55-64 Female 50k-75k Single No Own
2 <NA> Female <NA> <NA> <NA> <NA>
3 <NA> Male <NA> <NA> <NA> <NA>
4 <NA> Male <NA> <NA> <NA> <NA>
5 65+ Male 75k-100k Single No Own
6 <NA> Female <NA> <NA> <NA> <NA>
我已经阅读了有关该命令的其他帖子,但没有一个针对 NA 值的解决方案。我关注了一个关于Creating new dummy variable columns from categorical variables 的链接。我使用了第二个建议和二进制形式的数据,但代码不包含NA 值。
> #Use model.matrix function to
> binary1 <- model.matrix(~ factor(Store4df$HomeMarketValue) - 1)
> #Find which rows have NA values
> which(rowSums(is.na(binary1))==ncol(binary1))
# named integer(0)
> #Get head of model.matrix of two columns with five rows
> head(binary1, n=5)
factor(Store4df$HomeMarketValue)100k-150k factor(Store4df$HomeMarketValue)150k-200k
1 0 0
2 0 0
3 1 0
4 0 0
5 0 0
编辑:我忘了发布我有两种类型的分类变量。一个具有类别和NA 值,另一个具有TRUE 和NA 值。将具有TRUE 和NA 值的变量放入model.matrix 时出错。
> model.matrix(~ -1 + . , data = Store4df)
#Error in `contrasts<-`(`*tmp*`, value = contr.funs[1 + isOF[nn]]) :
contrasts can be applied only to factors with 2 or more levels
这是变量的样子:
> che <- Store4df$Pets
> summary(che)
Mode TRUE NA's
logical 3535 9628
将一个因子变量放入model.matrix后:
> data <- model.matrix(~ Pets, data = Store4df)
> summary(data)
(Intercept) PetsTRUE
Min. :1 Min. :1
1st Qu.:1 1st Qu.:1
Median :1 Median :1
Mean :1 Mean :1
3rd Qu.:1 3rd Qu.:1
Max. :1 Max. :1
如何在第 10 列和第 12:34 列中替换 TRUE 值?
【问题讨论】:
-
为什么需要这个?之后您打算如何处理这些数据? R 通常更喜欢分类数据保持因子形式而不是虚拟变量形式,然后根据需要应用对比。
-
@MrFlick 我将使用数据通过 CLUSTER 包中的 CLARA 函数执行聚类分析。我尝试使用 PAM,但无法预先创建数据集部分填充率的差异度量 b/c。我正在切换到一个数值算法,该算法采用样本而不是计算与每个观察值的距离。