[R] non-consing count

David Winsemius dwinsemius at comcast.net
Fri Jan 4 18:38:46 CET 2013

   On Jan 4, 2013, at 7:30 AM, Sam Steingold wrote:


     to count vector elements with some property, the standard idiom seems to

     be length(which):

     --8<---------------cut here---------------start------------->8---

     x <- c(1,1,0,0,0)

     count.0 <- length(which(x == 0))

     --8<---------------cut here---------------end--------------->8---

     however, this approach allocates and discards 2 vectors: a logical

     vector of length=length(x) and an integer vector in which.

     is there a cheaper alternative?

   I don't know if it is "cheaper", but the way I "learned to count" was:
   sum(x==8, na.rm=TRUE)
   David Winsemius
   Alameda, CA, USA

More information about the R-help mailing list