[R] creating empty cells with table()

Marc Schwartz MSchwartz at mn.rr.com
Wed Apr 19 15:34:51 CEST 2006


On Wed, 2006-04-19 at 09:21 -0400, Owen, Jason wrote:
> Hello,
> 
> Suppose I simulate 20 observations from the Poisson distribution
> with lambda = 4.  I can summarize these values using table() and
> then feed that to barplot() for a graph.
> 
> Problem: if there are empty categories (e.g. 0) or empty categories
> within the range of the data (e.g. observations for 6, 7, 9), barplot()
> does not include the empty cells in the x-axis of the plot.  Is there
> any way to specify table() to have specific categories (in the above
> example, probably 0:12) so that zeroes are included?
> 
> Thanks,
> 
> Jason

One thought comes to mind, which is based upon table()'s internal
behavior, where it interprets the vectors passed as a factor, for the
purpose of the [cross-]tabulation.

Thus:

> x <- rpois(20, 4)

> x
 [1] 4 4 3 8 2 4 5 2 3 2 4 5 5 5 6 4 5 8 2 5

> table(x)
x
2 3 4 5 6 8
4 2 5 6 1 2

# Add the desired factor levels
> table(factor(x, levels = 0:12))

 0  1  2  3  4  5  6  7  8  9 10 11 12
 0  0  4  2  5  6  1  0  2  0  0  0  0


For the barplot:

  barplot(table(factor(x, levels = 0:12)))


HTH,

Marc Schwartz




More information about the R-help mailing list