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

On 07/03/2012 05:18 PM, jin...@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

______________________________________________
R-help@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.

Reply via email to