Sofi Ummu Abdillah
Sofi Ummu Abdillah

Reputation: 13

table frequencies with custom column

For example, I have a matrix:

a <- c(2,3,4,3,3,2,2)
table(a)

output:

2 3 4 
3 3 1 

but the output i want is:

1 2 3 4 
0 3 3 1 

so from the example, actually the value range is 1 to 4.... because of the random value, the list may doesnt contain one or more element from the range when the value range is 1 to 4, i want the table have 4 coloumns with the not exist value filled by zero (0)

Upvotes: 1

Views: 54

Answers (1)

akrun
akrun

Reputation: 887951

You can convert 'a' to 'factor' and specify the levels before doing the table

table(factor(a, levels=seq_len(max(a))))
#1 2 3 4 
#0 3 3 1 

If you need a custom level that should be specified as well. Using the example from the comments,

a<- c(2,3,3,3,2,2)
table(factor(a, levels=1:4))
#1 2 3 4 
#0 3 3 0 

Upvotes: 4

Related Questions