Search code examples
rtabular

How to create frequency vector on a rating scale


I have a vector that contains values from 1 to 5:

c(4,5,5,5,1)

I need to get the frequency of the values expressed in a vector according to a rating scale of 1 to 5.

Scale: 1 2 3 4 5
Frequ: 1 0 0 1 3

So I try to achieve the following sequence:

c(1,0,0,1,3)

Does anybody now how to to this in R? I tried to use table and as.data.frame but I could not create that vector out of it. Any help is appreciated. Thank you.


Solution

  • This is a perfect example of where you can use a factor.

    ## Create example data
    d = c(4,5,5,5,1)
    ## Specify the appropriate
    d_fac = factor(d, levels = 1:5)
    

    Then use table as usal

    table(d_fac)
    # d_fac
    # 1 2 3 4 5 
    # 1 0 0 1 3