Search code examples
rdataframeuniquetabulate

Count unique occurrences within data frame


Let the table be as follows:

v1 v2 v3
A B A
B B A
A C
D C D

What i want R to create a table for number of occurences of unique values for each column:

v1 v2 v3
A 1 1
B 1 2
C 0 1
D 1 0

Solution

  • One option could be:

    sapply(df, function(x) table(factor(x, levels = unique(unlist(df)))))
    
      V1 v2 v3
    A  1  1  2
    B  1  2  0
    D  1  0  1
    C  0  1  1