简体   繁体   中英

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.

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?

Any insight or assistance would be greatly appreciated!

A vectorized solution with max.col :

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

As an alternative solution, you could use 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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