Search notes:

R function: table

Count frequency of a vector

table applied on a vector counts the frequencies of its elements
vec <- c('ABC', 'DEF', 'ABC', 'ABC', 'GHI', 'DEF', 'ABC')
table(vec)
#
# vec
# ABC DEF GHI 
#   4   2   1 

table(factor(vec))
#
#
# ABC DEF GHI
#   4   2   1
Github repository about-r, path: /functions/table/frequency.R

Contigency table

If two vectors are passed to the table function, it returns a contingency table (aka cross tabulation)
contigency_table  <- table(c('AAA', 'AAA', 'BBB', 'AAA', 'AAA', 'CCC', 'BBB', 'BBB', 'AAA'),
                           c('yyy', 'yyy', 'qqq', 'yyy', 'qqq', 'iii', 'yyy', 'qqq', 'iii')
                          );
contigency_table;
# 
#       iii qqq yyy
#   AAA   1   1   3
#   BBB   0   2   1
#   CCC   1   0   0

attributes(contigency_table);
# $dim
# [1] 3 3
# 
# $dimnames
# $dimnames[[1]]
# [1] "AAA" "BBB" "CCC"
# 
# $dimnames[[2]]
# [1] "iii" "qqq" "yyy"
# 
# 
# $class
# [1] "table"
Github repository about-r, path: /functions/table/contigency.R

N-Way contigency table

It is also possible to create a *three-way contigency table (or more generally, an n-way contigency table):
n_way_ct <- table(c("AAA", "AAA", "BBB", "AAA", "AAA", "CCC", "BBB", "BBB", "AAA"),
                  c("yyy", "yyy", "qqq", "yyy", "qqq", "iii", "yyy", "qqq", "iii"),
                  c("___", "###", "___", "___", "###", "___", "___", "###", "???")
              );

n_way_ct;
#
# , ,  = ###
# 
#      
#       iii qqq yyy
#   AAA   0   1   1
#   BBB   0   1   0
#   CCC   0   0   0
# 
# , ,  = ???
# 
#      
#       iii qqq yyy
#   AAA   1   0   0
#   BBB   0   0   0
#   CCC   0   0   0
# 
# , ,  = ___
# 
#      
#       iii qqq yyy
#   AAA   0   0   2
#   BBB   0   1   1
#   CCC   1   0   0
Github repository about-r, path: /functions/table/3-way-contingency-table.R

See also

unique
table can be used to count the occurrence of the different elements in a vector.
table is the generic form of tapply.
The underlying function for table is tabulate.
ftable
Exploring R objects
Index to (some) R functions

Index