Melt a dummy matrix into a column

If I have a factor variable, say x = factor(c(1, 2, 3)), then I can use the function model.matrixto create a dummy matrix:

model.matrix(~x + 0)

and I will get a matrix like:

  x1 x2 x3
1  1  0  0
2  0  1  0
3  0  0  1

My question is, if I already have a large dummy matrix, how can I melt it to a column (factor)?

In another world, is there an inverse function of model.matrix?

+4
source share
1 answer

apply suitable for that.

I will use caretpackage data carsthat has 1-0 data instead of car types in factor format. Allow to convert the 5 column ( convertible, coupe, hatchback, sedan, wagon) into a single-factor variable Type.

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
+2
source

All Articles