user3855285
user3855285

Reputation: 21

R table function

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

Answers (2)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

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

MrFlick
MrFlick

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

Related Questions