1

I wanted to create a vector of counts if possible. For example: I have a vector

x <- c(3, 0, 2, 0, 0)

How can I create a frequency vector for all integers between 0 and 3? Ideally I wanted to get a vector like this:

> 3 0 1 1

which gives me the counts of 0, 1, 2, and 3 respectively.

Much appreciated!

Lin
  • 93
  • 8
  • Possible duplicate of [Create the frequency count from a vector in R](http://stackoverflow.com/questions/20869374/create-the-frequency-count-from-a-vector-in-r) – catastrophic-failure Aug 02 '16 at 12:40
  • 2
    Possible duplicate of [counting the number of each letter in a vector of strings](http://stackoverflow.com/questions/19476210/counting-the-number-of-each-letter-in-a-vector-of-strings) – jogo Oct 12 '16 at 07:40
  • This is a duplicate, but above 2 links are not the right ones. – zx8754 Oct 12 '16 at 07:49

3 Answers3

4

You can do

table(factor(x, levels=0:3))

Simply using table(x) is not enough.

Or with tabulate which is faster

tabulate(factor(x, levels = min(x):max(x)))
akrun
  • 874,273
  • 37
  • 540
  • 662
Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
  • I tried that, but it gives me an error, Error in factor(gaps, labels = 0:3) : invalid 'labels'; length 4 should be 1 or 3 – Lin Aug 02 '16 at 09:14
  • 2
    Maybe a bit "robuster" way would be `r <- range(x) ; table(factor(x, levels = r[1]:r[2]))` – David Arenburg Aug 02 '16 at 09:30
2

You can just use table():

a <- table(x)
a
x
#0 2 3 
#3 1 1 

Then you can subset it:

a[names(a)==0]
#0 
#3

Or convert it into a data.frame if you're more comfortable working with that:

u<-as.data.frame(table(x))
u
#  x Freq
#1 0 3
#2 2 1
#3 3 1

Edit 1: For levels:

a<- as.data.frame(table(factor(x, levels=0:3)))
catastrophic-failure
  • 3,759
  • 1
  • 24
  • 43
Sayali Sonawane
  • 12,289
  • 5
  • 46
  • 47
2

You can do this using rle (I made this in minutes, so sorry if it's not optimized enough).

x = c(3, 0, 2, 0, 0)
r = rle(x)
f = function(x) sum(r$lengths[r$values == x])
s = sapply(FUN = f, X = as.list(0:3))
data.frame(x = 0:3, freq = s)
#> data.frame(x = 0:3, freq = s)
#  x freq
#1 0    3
#2 1    0
#3 2    1
#4 3    1
catastrophic-failure
  • 3,759
  • 1
  • 24
  • 43