简体   繁体   English

R将几个虚拟变量列合并为1

[英]R Merge Several Dummy Variable Columns into 1

I am trying to merge several columns in the cars data frame (caret package). 我正在尝试合并汽车数据框(插入符号包)中的几个列。 The columns "convertible, coupe, hatchback, sedan, wagon" have dummy variables and I would like to create 1 column named type with the column names depending on the type of vehicle. 列“敞篷车,轿跑车,掀背车,轿车,旅行车”都有虚拟变量,我想创建一个名为type的列,其列名取决于车辆的类型。

library(caret)
data(cars)
head(cars)
colnames(cars)

Below are the column names of the cars data frame: 以下是汽车数据框的列名:

 [1] "Price"       "Mileage"     "Cylinder"    "Doors"       "Cruise"        
 [6] "Sound"       "Leather"     "Buick"       "Cadillac"    "Chevy"     
[11] "Pontiac"     "Saab"        "Saturn"      "convertible" "coupe"   
[16] "hatchback"   "sedan"       "wagon" 

How can I merge/consolidate the last 5 dummy variable columns into 1 with the corresponding vehicle type? 如何将最后5个虚拟变量列合并/合并为1与相应的车辆类型?

Any insight or assistance would be greatly appreciated! 任何见解或帮助将不胜感激!

A vectorized solution with max.col : max.col的矢量化解决方案:

cars$type <- names(cars[14:18])[max.col(cars[14:18])]

As an alternative solution, you could use match : 作为替代解决方案,您可以使用match

cars$type <- names(cars[14:18])[apply(cars[14:18], 1, match, x = 1)] 
ind <- apply(cars[,14:18],1,function(x) which(as.logical(x)))
cars$type <- colnames(cars[,14:18])[ind]
head(cars)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM