Christopher DuBois - 1 year ago 87

R Question

I have a vector of integers between 0 and 5. I want to compute a histogram of counts. For example:

`y <- c(0, 0, 1, 3, 4, 4)`

table(y)

# y

# 0 1 3 4

# 2 1 1 2

However, I also want the results to include the fact that there are zero 2's and zero 5's, ie. I want the returned vector to have length 6. Can I use

`table()`

Desired result:

`# y`

# 0 1 2 3 4 5

# 2 1 0 1 2 0

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

If you convert y to a factor, the missing factor levels will also appear in the table

```
> y <- c(0,0,1,3,4,4)
> table(factor(y, levels=0:5))
0 1 2 3 4 5
2 1 0 1 2 0
```