Eric
Eric

Reputation: 1389

How to use tabulate function to count zeros?

I am trying to count integers in a vector that also contains zeros. However, tabulate doesn't count the zeros. Any ideas what I am doing wrong?

Example:

> tabulate(c(0,4,4,5))
[1] 0 0 0 2 1

but the answer I expect is:

[1] 1 0 0 0 2 1

Upvotes: 2

Views: 174

Answers (2)

András Aszódi
András Aszódi

Reputation: 9660

I got annoyed enough by tabulate to write a short function that can count not only the zeroes but any other integers in a vector:

my.tab <- function(x, levs) {
  sapply(levs, function(n) {
    length(x[x==n])
  }
)}

The parameter x is an integer vector that we want to tabulate. levs is another integer vector that contains the "levels" whose occurrences we count. Let's set x to some integer vector:

x <- c(0,0,1,1,1,2,4,5,5)

A) Use my.tab to emulate R's built-in tabulate. 0-s will be ignored:

my.tab(x, 1:max(x))
# [1] 3 1 0 1 2

B) Count the occurrences of integers from 0 to 6:

my.tab(x, 0:6)
# [1] 2 3 1 0 1 2 0

C) If you want to know (for some strange reason) only how many 1-s and 4-s your x vector contains, but ignore everything else:

my.tab(x, c(1,4))
# [1] 3 1

Upvotes: 0

Maurits Evers
Maurits Evers

Reputation: 50668

Use a factor and define its levels

tabulate(factor(c(0,4,4,5), 0:5))
#[1] 1 0 0 0 2 1

The explanation for the behaviour you're seeing is in ?tabulate (bold face mine)

bin: a numeric vector (of positive integers), or a factor. Long vectors are supported.

In other words, if you give a numeric vector, it needs to have positive >0 integers. Or use a factor.

Upvotes: 2

Related Questions