Re: [R] how to convert multiple dummy variables to 1 factor variable?

From: Marc Schwartz <MSchwartz_at_mn.rr.com>
Date: Sun 22 Oct 2006 - 02:12:12 GMT

On Sat, 2006-10-21 at 21:04 -0400, Wensui Liu wrote:
> Dear Listers,
>
> I am wondering how to convert multiple dummy variables to 1 factor variable.
>
> Thanks.
>
> wensui

I was thinking of a function that is essentially the reverse of model.matrix() which is used by R modeling functions. I did not see one, though it is possible that I missed it.

However, I suppose that something along the lines of the following would work.

Say we have a matrix as follows, where the columns represent the presence or absence of the factor levels, as one would see in a model matrix. There should be a single '1' in each row as each row corresponds to a single observation.

> mat

     Level1 Level2 Level3 Level4 Level5
[1,]      0      1      0      0      0
[2,]      1      0      0      0      0
[3,]      0      0      0      1      0
[4,]      0      0      1      0      0
[5,]      0      0      0      0      1


# Create a new factor based upon the index of each 1 in each row # Use the matrix column names as the labels for each level NewFactor <- factor(apply(mat, 1, function(x) which(x == 1)),

                    labels = colnames(mat))

> NewFactor

[1] Level2 Level1 Level4 Level3 Level5
Levels: Level1 Level2 Level3 Level4 Level5

HTH, Marc Schwartz



R-help@stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code. Received on Sun Oct 22 12:16:15 2006

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Sun 22 Oct 2006 - 08:30:11 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.