Wednesday, October 12, 2011

Contingency table in R using table()

An Introduction to R
http://cran.r-project.org/doc/manuals/R-intro.html

Frequency, contingency table in R using table()

http://www.statmethods.net/stats/frequencies.html


table

You can generate frequency tables using the table( ) function, tables of proportions using the prop.table( ) function, and marginal frequencies using margin.table( ).


a <- rep(c(NA, 1/0:3), 10)

> a
[1]        NA       Inf 1.0000000 0.5000000 0.3333333        NA       Inf
[8] 1.0000000 0.5000000 0.3333333        NA       Inf 1.0000000 0.5000000
[15] 0.3333333        NA       Inf 1.0000000 0.5000000 0.3333333        NA
[22]       Inf 1.0000000 0.5000000 0.3333333        NA       Inf 1.0000000
[29] 0.5000000 0.3333333        NA       Inf 1.0000000 0.5000000 0.3333333
[36]        NA       Inf 1.0000000 0.5000000 0.3333333        NA       Inf
[43] 1.0000000 0.5000000 0.3333333        NA       Inf 1.0000000 0.5000000
[50] 0.3333333


> table(a)
a
0.333333333333333               0.5                 1               Inf
               10                10                10                10

-----------------


# 2-Way Frequency Table
attach(mydata)
A <- letters[1:3]
B <- sample(a)
mytable <- table(A,B) # A will be rows, B will be columns

> mytable # print table
#   B
#A   a b c
#  a 0 1 0
#  b 1 0 0
#  c 0 0 1

margin.table(mytable, 1) # A frequencies (summed over B)
margin.table(mytable, 2) # B frequencies (summed over A)
prop.table(mytable) # cell percentages
prop.table(mytable, 1) # row percentages
prop.table(mytable, 2) # column percentages

No comments: