[R] count appearence of zero in a vector

Suzen, Mehmet msuzen at gmail.com
Fri Jan 4 06:27:18 CET 2013


Hi Hermann,

You may want to use ?which, to store the index as well (might be handy
in debugging or some other
purposes if zeros has some special meaning) :

test <- c(1, 1, 1 , 1 , 1, 1, 2, 1, 1, 1, 0, 2, 0, 1, 1, 0, 0, 0, 1,
1, 1, 0, 1, 2, 1, 1, 1, 1, 1, 1)
length(which(test==0))

But be careful when using == 0. If you are sure that elements are all
integers I prefer this

length(which(test <1)).

Or a safe tolerance value from .Machine, if you are dealing with double numbers.

length(which(test < .Machine$double.xmin))


-m




More information about the R-help mailing list