R 将虚拟矩阵熔化到列中
如果我有一个因子变量,比如说R 将虚拟矩阵熔化到列中,r,model.matrix,R,Model.matrix,如果我有一个因子变量,比如说x=factor(c(1,2,3)),那么我可以使用model.matrix函数生成一个虚拟矩阵: model.matrix(~x + 0) 我会得到一个矩阵,如: x1 x2 x3 1 1 0 0 2 0 1 0 3 0 0 1 我的问题是,如果我已经有一个大的虚拟矩阵,我怎么能把它融化回(因子)列 在另一个世界中,是否存在模型的反函数。矩阵?应用适用于此 我将使用caret软件包的cars数据,该数据具有1-0数据,而不是因子格式的汽车类
x=factor(c(1,2,3))
,那么我可以使用model.matrix
函数生成一个虚拟矩阵:
model.matrix(~x + 0)
我会得到一个矩阵,如:
x1 x2 x3
1 1 0 0
2 0 1 0
3 0 0 1
我的问题是,如果我已经有一个大的虚拟矩阵,我怎么能把它融化回(因子)列
在另一个世界中,是否存在模型的反函数。矩阵?
应用
适用于此
我将使用caret
软件包的cars
数据,该数据具有1-0数据,而不是因子格式的汽车类型。让我们将这5列(敞篷车、双门轿跑车、掀背车、轿车、货车
)转换为单因素变量,类型
library(caret)
data(cars)
head(cars[,-c(1:13)])
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
cars$Type = as.factor(apply(df,1,function(foo){return(names(df)[which.max(foo)])}))
head(cars[,-c(1:13)])
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
假设您的数据名为df,您可以尝试
应用(df,1,which.max)
@mamounbenghzal,这对c(1,2,3)
@davidernburg以外的任何向量都不起作用,为什么?这是诚信的证明set.seed(1);x@mamounbenghzal您太努力了,尝试设置x无论如何,似乎最好的解决方案是因子(sub(“x”),colnames(modmat)[max.col(modmat)],fixed=TRUE))
。唯一的问题是,您必须知道传递到model.matrix
(在本例中是x
)的向量的名称