Bayes
Bayes

Reputation: 71

Melt a dummy matrix to a column

If I have a factor variable, say x = factor(c(1, 2, 3)), then I can use model.matrix function to generate 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 that, if I already have a large dummy matrix, how could I melt it back to a (factor) column?

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

Upvotes: 4

Views: 1149

Answers (1)

Özgür
Özgür

Reputation: 8247

apply is suitable for this.

I will use caret package's cars data, which has 1-0 data instead of car types in factor format. Let's convert these 5 columns (convertible, coupe, hatchback, sedan, wagon) to 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

Upvotes: 3

Related Questions