[R] create dummy variables by for loop

David Winsemius dwinsemius at comcast.net
Thu Feb 24 20:30:56 CET 2011


On Feb 24, 2011, at 1:23 PM, Changbin Du wrote:

> 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

You are creating only one new column named ack$id_

Putting the "[" operator with a numeric argument after does not name a  
new column.

>                     }
> But only one column is created, can anyone help me?

If I tell you how to do that I would only be hurting you. You should  
be using factors. The modeling functions should all be capable of  
accepting them and if you are writing your own then it seems only  
sensible that you follow their example.

>


-- 

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list