Search code examples
rdatasetfrequency

Convert the frequencies of a list elements (table) to data frame in R


I have a list like this:

 x = c(0,0,1,1,2,3,1,0,4,5,6,4,3,2,1,1,0,2,3)

and I need to create a dataframe with frequencies, where col names are the unique elements of my list,and the row contains the frequencies

If I call

table(x)

I get what I want but it's not dataframe

x
0 1 2 3 4 5 6 
4 5 3 3 2 1 1 

I would like to have a data frame like this:

> mydf
  0 1 2 3 4 5 6
1 4 5 3 3 2 1 1

Solution

  • A bit excessive but

    mydf <- as.data.frame(t(as.matrix(table(x))))
    

    gives

    > mydf
      0 1 2 3 4 5 6
    1 4 5 3 3 2 1 1