R 将几个虚拟变量列合并为 1 [英] R Merge Several Dummy Variable Columns into 1
问题描述
我正在尝试合并汽车数据框(插入符号包)中的几列.敞篷车、轿跑车、掀背车、轿车、旅行车"列有虚拟变量,我想创建 1 个名为 type 的列,列名取决于车辆的类型.
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"
如何将最后 5 个虚拟变量列与相应的车辆类型合并/合并为 1 个?
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!
推荐答案
使用 max.col
的矢量化解决方案:
A vectorized solution with max.col
:
cars$type <- names(cars[14:18])[max.col(cars[14:18])]
作为替代解决方案,您可以使用 match
:
As an alternative solution, you could use match
:
cars$type <- names(cars[14:18])[apply(cars[14:18], 1, match, x = 1)]
这篇关于R 将几个虚拟变量列合并为 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!