[R] create dummy variables by for loop
Dimitri Liakhovitski
dimitri.liakhovitski at gmail.com
Thu Feb 24 20:43:24 CET 2011
If your ack$ID variable is numeric, you could first turn it into a factor:
myfactor = as.factor(ack$ID)
And then use model.matrix to create dummy variables:
mydummies = model.matrix(~myfactor)[, -1]
You'll get as many dummy variables as values you have in ack$ID -
minus 1 (for the reference level).
Dimitri
On Thu, Feb 24, 2011 at 2:30 PM, Changbin Du <changbind at gmail.com> wrote:
> Thanks to all, appreciated!
>
> On Thu, Feb 24, 2011 at 11:18 AM, Jonathan P Daily <jdaily at usgs.gov> wrote:
>
>> See inline below.
>> --------------------------------------
>> Jonathan P. Daily
>> Technician - USGS Leetown Science Center
>> 11649 Leetown Road
>> Kearneysville WV, 25430
>> (304) 724-4480
>> "Is the room still a room when its empty? Does the room,
>> the thing itself have purpose? Or do we, what's the word... imbue it."
>> - Jubal Early, Firefly
>>
>> r-help-bounces at r-project.org wrote on 02/24/2011 01:23:54 PM:
>>
>> > [image removed]
>> >
>> > [R] create dummy variables by for loop
>> >
>> > Changbin Du
>> >
>> > to:
>> >
>> > <r-help at r-project.org>
>> >
>> > 02/24/2011 01:25 PM
>> >
>> > Sent by:
>> >
>> > r-help-bounces at r-project.org
>> >
>> > HI, Dear R community,
>> >
>> > I try to create 100 dummy variables like the following:
>> >
>> > ack$id_1 <- (ack$ID==1)*1
>> > ack$id_2 <- (ack$ID==2)*1
>> > ..
>> > .
>> > ack$id_100 <- (ack$ID==100)*1
>> >
>> >
>> > I used the following codes:
>> >
>> > for(i in 1:100){
>> > ack$id_[i] <- (ack$ID==i)*1
>> > }
>> This doesn't do what you think it does. when i = 1, it assigns the result
>> of (ack$ID==1)*1 to the first element of ack$id_
>>
>> If you want ack$id_i to be created, try:
>>
>> ack[[paste("id", i, sep = "_")]] <- (ack$ID==i)*1
>>
>>
>> >
>> > But only one column is created, can anyone help me?
>> >
>> > Thanks a lot!
>> >
>> >
>> > --
>> > Sincerely,
>> > Changbin
>> > --
>> >
>> > [[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<http://www.r-project.org/posting-guide.html>
>> > and provide commented, minimal, self-contained, reproducible code.
>>
>>
>
>
> --
> Sincerely,
> Changbin
> --
>
> Changbin Du
> DOE Joint Genome Institute
> Bldg 400 Rm 457
> 2800 Mitchell Dr
> Walnut Creet, CA 94598
> Phone: 925-927-2856
>
> [[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.
>
--
Dimitri Liakhovitski
Ninah Consulting
www.ninah.com
More information about the R-help
mailing list