Home > OS >  Counting zero frequency of a vector in R
Counting zero frequency of a vector in R

Time:02-26

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.

CodePudding user response:

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

CodePudding user response:

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 
  •  Tags:  
  • r
  • Related