1

I have created a sample with replacement as follows and I would to have the frequency of each element of the vector, however by table function in R, I only get the frequency of the elements that appear on the sample. How can I get the zero frequencies for the rest of elements that not appear in the sample.

        > t = 1:15
        > x = sample(t, 10, replace=TRUE)
        > table(x)
        x
        2  3  4  5  6  7  8 10 
        1  1  1  2  1  1  2  1 

As the output I would like to have a data.frame where the first column is 1:15 and the second column is the frequencies of each element.

shany
  • 175
  • 1
  • 1
  • 7

2 Answers2

3

You can use as.factor

> v <- 1:15

> x <- sample(as.factor(v), 10, replace = TRUE)

> table(x)
x
 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15
 0  1  0  0  2  1  1  0  1  0  0  0  2  2  0
ThomasIsCoding
  • 96,636
  • 9
  • 24
  • 81
1

I prefer what Thomas has presented, but if you want to directly use your existing inputs, here is another way

t = 1:15
x = sample(t, 10, replace=TRUE)

setNames(sapply(t,function(t) sum(t==x)), nm=t)

 1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 
 0  2  1  0  0  1  0  1  1  0  1  0  1  1  1 
langtang
  • 22,248
  • 1
  • 12
  • 27