汽车的type为5个类型:"convertible", "coupe", "hatchback", "sedan", "wagon"(“敞篷车”,“轿跑车”,“掀背车”,“轿车”,“旅行车”)
在目前的数据集中,5个类型为5个变量,每个变量取值为0或1:
head(cars[14:18])
convertible coupe hatchback sedan wagon
1 0 0 0 1 0
2 0 1 0 0 0
3 1 0 0 0 0
4 1 0 0 0 0
5 1 0 0 0 0
6 1 0 0 0 0
为了将上述5个变量合为1个type变量,可用以下代码:
type <- c("convertible", "coupe", "hatchback", "sedan", "wagon")
cars$Type <- factor(apply(cars[, 14:18], 1, function(x) type[which(x == 1)]))
结果为:
最后新加了一个type字段
> head(cars[14:19])
convertible coupe hatchback sedan wagon Type
1 0 0 0 1 0 sedan
2 0 1 0 0 0 coupe
3 1 0 0 0 0 convertible
4 1 0 0 0 0 convertible
5 1 0 0 0 0 convertible
6 1 0 0 0 0 convertible