[R] Is it possible to remove this loop? [SEC=UNCLASSIFIED]

David Winsemius dwinsemius at comcast.net
Tue Jul 3 14:52:37 CEST 2012


On Jul 3, 2012, at 5:08 AM, Jim Lemon wrote:

> On 07/03/2012 05:18 PM, Jin.Li at ga.gov.au wrote:
>> Hi all,
>>
>> I would like create a new column in a data.frame (a1) to store 0, 1  
>> data converted from a factor as below.
>>
>> a1$h2<-NULL
>> for (i in 1:dim(a1)[1]) {
>>       if (a1$h1[i]=="H") a1$h2[i]<-1 else a1$h2[i]<-0
>>       }
>>
>> My question: is it possible to remove the loop from above code to  
>> achieve the desired result?
>>
> Hi Jin,
> Just to provide you with an embarrassment of alternatives:
>
> a1$h2<-ifelse(a1$h1=="H",1,0)

One more. Similar to Petr's, but perhaps a bit more accessible to a  
new R user:

a1$h2 <- as.numeric(a1$h1=="H")

I wasn't sure whether NA's would be handled in the same manner by  
these two methods so I tested:

 > ifelse( factor(c("H", "h", NA))=="H", 1, 0)
[1]  1  0 NA
 > as.numeric( factor(c("H", "h", NA))=="H")
[1]  1  0 NA

-- 
David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list