[R] weird apply() behavior

array chip arrayprofile at yahoo.com
Tue Aug 30 02:02:47 CEST 2011


Hi, I had a weird results from using apply(). Here is an simple example:

> y<-data.frame(list(a=c(1,NA),b=c('2k','0')))
> y

    a     b
1  1   2k
2 NA   0

> apply(y,1,function(x){x<-unlist(x); if (!is.na(x[2]) & x[2]=='2k' & !is.na(x[1]) & x[1]=='1') 1 else 0} )

This should print "1 0" as output, as demonstrated by:

> apply(y[1,],1,function(x){x<-unlist(x); if (!is.na(x[2]) & x[2]=='2k' & !is.na(x[1]) & x[1]=='1') 1 else 0} )
1 
1 
> apply(y[2,],1,function(x){x<-unlist(x); if (!is.na(x[2]) & x[2]=='2k' & !is.na(x[1]) & x[1]=='1') 1 else 0} )
2 
0 


But it actually prints:

> apply(y,1,function(x){x<-unlist(x); if (!is.na(x[2]) & x[2]=='2k' & !is.na(x[1]) & x[1]=='1') 1 else 0} )

[1] 0 0


Anyone has any suggestion?

Thanks

John




More information about the R-help mailing list