Message-ID: <6E08F082-06A5-4240-B92D-DB46FDC52791@comcast.net>
Date: 2012-07-03T12:52:37Z
From: David Winsemius
Subject: Is it possible to remove this loop? [SEC=UNCLASSIFIED]
In-Reply-To: <4FF2B6A3.5040808@bitwrit.com.au>
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