[R] weird apply() behavior

David Winsemius dwinsemius at comcast.net
Tue Aug 30 02:17:47 CEST 2011


On Aug 29, 2011, at 8:02 PM, array chip wrote:

> 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);

That is quite unnecessary since apply coerces the rows into vectors  
whether you want it to or not,

>> if (!is.na(x[2]) & x[2]=='2k' & !is.na(x[1]) & x[1]=='1') 1 else 0} )

So everything get coerced to character and I suspect NA -> "NA" or  
NA_character and so !is.na() gives the wrong result. Try printing  
str(x) inside that apply loop.

-- 
David.



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

David Winsemius, MD
West Hartford, CT



More information about the R-help mailing list