Reputation: 21
If I have a vector numbers <- c(1,1,2,4,2,2,2,2,5,4,4,4)
, and I use 'table(numbers)', I get
names 1 2 4 5
counts 2 5 4 1
What if I want it to include 3 also or generally, all numbers from 1:max(numbers)
even if they are not represented in numbers. Thus, how would I generate an output as such:
names 1 2 3 4 5
counts 2 5 0 4 1
Upvotes: 0
Views: 345
Reputation: 193687
For this particular example (positive integers), tabulate
would also work:
numbers <- c(1,1,2,4,2,2,2,2,5,4,4,4)
tabulate(numbers)
# [1] 2 5 0 4 1
Upvotes: 1
Reputation: 206566
If you want R to add up numbers that aren't there, you should create a factor and explicitly set the levels. table
will return a count for each level.
table(factor(numbers, levels=1:max(numbers)))
# 1 2 3 4 5
# 2 5 0 4 1
Upvotes: 3