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

Jim Lemon jim at bitwrit.com.au
Tue Jul 3 11:08:51 CEST 2012


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)

Jim



More information about the R-help mailing list