0

我需要将调查数据框中的少量分类变量转换为虚拟变量。变量按类型(例如食物类型)分组,并且在每种类型的调查中,受访者对他们的第一、第二和第三偏好进行了排名。每种类型的可用选项列表相似但不相同。我的问题是我想强制类别选择的超集在每种情况下都进行虚拟编码。

set.seed(1)
d<-data.frame(foodtype1rank1=sample(c('noodles','rice','cabbage','pork'),5,replace=T),
              foodtype1rank2=sample(c('noodles','rice','cabbage','pork'),5,replace=T),
              foodtype1rank3=sample(c('noodles','rice','cabbage','pork'),5,replace=T),
              foodtype2rank1=sample(c('noodles','rice','cabbage','tuna'),5,replace=T),
              foodtype2rank2=sample(c('noodles','rice','cabbage','tuna'),5,replace=T),
              foodtype2rank3=sample(c('noodles','rice','cabbage','tuna'),5,replace=T),
              foodtype3rank1=sample(c('noodles','rice','cabbage','pork','mackerel'),5,replace=T),
              foodtype3rank2=sample(c('noodles','rice','cabbage','pork','mackerel'),5,replace=T),
              foodtype3rank3=sample(c('noodles','rice','cabbage','pork','mackerel'),5,replace=T))

回顾一下,model.matrix() 将为任何单个变量创建虚拟变量:

model.matrix(~d[,1]-1)
  d[, 1]cabbage d[, 1]noodles d[, 1]pork d[, 1]rice
1             0             0          0          1
2             0             0          0          1
3             1             0          0          0
4             0             0          1          0
5             0             1          0          0

或通过 sapply() 获取所有变量:

sapply(d,function(x) model.matrix(~x-1))

自然,model.matrix() 只会分别考虑每个因素中存在的水平。但我想强制为每种类型包含完整的食物类型:面条、米饭、卷心菜、猪肉、金枪鱼、鲭鱼。在此示例中,将生成 54 个虚拟变量(3 个类型 x 3 个等级 x 6 个类别)。我假设我会以某种方式将完整的集合显式传递给 model.matrix(),但看不到如何。

最后,我知道 R 模型会在内部自动生成虚拟代码因子,但我仍然需要这样做,包括在 R 外部导出。

4

1 回答 1

2

实现这一点的最佳方法是明确指定每个因素的水平:

d$foodtype1rank1=factor(sample(c('noodles','rice','cabbage','pork'), 5, replace=T), 
                        levels=c('noodles','rice','cabbage','pork','mackerel'))

当您知道数据时,这始终是一个好习惯。

于 2015-02-19T14:33:15.390 回答