r-按名称合并多个伪变量列



我的问题如下

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

预期答案

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

但是使用诸如下面这样的列的名称是不起作用的。如何处理这件事?非常感谢。

cars$type <- cars[c("convertible", "coupe", "hatchback", "sedan", "wagon" )][apply(cars[c("convertible", "coupe", "hatchback", "sedan", "wagon" )], 1, match, x = 1)] 

头(车(

您可以以类似的方式按名称对数据帧进行子集设置-

cols <- c("convertible", "coupe", "hatchback", "sedan", "wagon" )
cars$type <- cols[max.col(cars[cols])] 

检查输出-

identical(cols[max.col(cars[cols])] , names(cars[14:18])[max.col(cars[14:18])])
#[1] TRUE

最好指定ties.method,否则可以选择"random"作为默认值,这可能会改变每行有多个max值的每次运行的结果

cols <- c("convertible", "coupe", "hatchback", "sedan", "wagon" )
cars$type <- cols[max.col(cars[cols], "first")]

最新更新