Hi Ista,

I was doing about something similar when I saw your post, so I took your
code and did some timings:

> system.time(replicate(1000000, count.0 <- length(which(x == 0))))
   user  system elapsed
  5.590   0.173   5.834
> system.time(replicate(1000000, count.1 <- sum(x == 0)))
   user  system elapsed
  5.043   0.064   5.095
> all.equal(count.0, count.1)
[1] TRUE

> sessionInfo()
R version 2.15.2 Patched (2012-10-31 r61060)
Platform: x86_64-apple-darwin9.8.0/x86_64 (64-bit)

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

 So there is some time difference there ;-)

Best,
Jorge.-



On Sat, Jan 5, 2013 at 2:43 AM, Ista Zahn <> wrote:

> Hi Sam,
>
> Here is one alternative, which is at least faster:
>
> system.time(count.0 <- length(which(x == 0)))
> system.time(count.1 <- sum(x == 0))
> all.equal(count.0, count.1)
>
> Best,
> Ista
>
> On Fri, Jan 4, 2013 at 10:30 AM, Sam Steingold <> wrote:
> > Hi,
> > 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?
> > Thanks!
> >
> > --
> > Sam Steingold (http://sds.podval.org/) on Ubuntu 12.04 (precise) X
> 11.0.11103000
> > http://www.childpsy.net/ http://iris.org.il http://honestreporting.com
> > http://jihadwatch.org http://pmw.org.il
> http://www.PetitionOnline.com/tap12009/
> > War doesn't determine who's right, just who's left.
> >
> > ______________________________________________
> > 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.
>
> ______________________________________________
> 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.
>

	[[alternative HTML version deleted]]


