[R] create dummy variables by for loop

Jonathan P Daily jdaily at usgs.gov
Thu Feb 24 20:18:19 CET 2011


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
> and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list