Re: [R] Converting a categorical variable to multiple dichotemousvariables

From: Dr. Pablo E. Verde <PabloEmilio.Verde_at_uni-duesseldorf.de>
Date: Tue, 12 Apr 2011 14:52:30 +0200

Hi Shane,

An alternative is:

cat<-as.factor(c(1,1,3,2,4))
outer(cat, levels(cat), "==")+0

Cheers,

Pablo

> hi:
> here is one solution:
>
> cat<-as.factor(c(1,1,3,2,4))
> model.matrix(~cat-1,cat)
>
> cbind(cat,model.matrix(~cat-1,cat))
> Andrija
>
> On Tue, Apr 12, 2011 at 2:17 PM, Shane Phillips
> <SPhillips_at_lexington1.net>wrote:
>
>> I have a categorical variable in a dataframe similar to the following...
>>
>> cat
>> 1
>> 1
>> 3
>> 2
>> 4
>>
>> I need to convert it to 4 dichotemous variables for each observations
>> like...
>>
>> cat1 cat2 cat3 cat4
>> 1 0 0 0
>> 1 0 0 0
>> 0 0 1 0
>> 0 1 0 0
>> 0 0 0 1
>>
>>
>> Thanks in advance!
>>
>> Shane
>>
>> ______________________________________________
>> R-help_at_r-project.org mailing list
>> https://stat.ethz.ch/mailman/listinfo/r-help
>> PLEASE do read the posting guide
>> http://www.R-project.org/posting-guide.html<http://www.r-project.org/posting-guide.html>
>> and provide commented, minimal, self-contained, reproducible code.
>>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help_at_r-project.org 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.
>



R-help_at_r-project.org 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 Tue 12 Apr 2011 - 12:55:06 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 12 Apr 2011 - 15:20:29 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.

list of date sections of archive