On Aug 29, 2011, at 8:17 PM, David Winsemius wrote:


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.

I was wrong abut my diagnosis but my methods were sound.
This is str from the first row:
Named chr [1:2] " 1" "2k"

So probably the default stringsAsFactors rule created "b" as a factor and something else made that integer `1` turn into " 1" .

--
DA\avid.



--
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@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

______________________________________________
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.

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