Skip to content

Instantly share code, notes, and snippets.

@geofferyzh
Created May 23, 2012 16:51
Show Gist options
  • Save geofferyzh/2776323 to your computer and use it in GitHub Desktop.
Save geofferyzh/2776323 to your computer and use it in GitHub Desktop.
RinAction - Basic Statistics - Frequency Table
#-----------------------------------------------------------------------------#
#-----------------------------------------------------------------------------#
# R in Action - Basic Statistics
# - Frequency Table
#-----------------------------------------------------------------------------#
#-----------------------------------------------------------------------------#
install.packages(c('npmc', 'ggm', 'gmodels', 'vcd', 'Hmisc','pastecs', 'psych', 'doBy', 'reshape'))
#######################################################
#######################################################
# -------- Frequency and Contingency Table ---------- #
#######################################################
#######################################################
# get Arthritis data
library(vcd)
###################################
### 1. One-Way Tables
###################################
# one way table
mytable <- with(Arthritis, table(Improved))
mytable
prop.table(mytable)
prop.table(mytable)*100
###################################
### 2. Two-Way Tables Using Table()
###################################
# two-way frequency using table()
mytable <- with(Arthritis,table(Treatment, Improved, useNA="ifany")) # by default ignore missing
mytable
# two-way freq using xtabs()
mytable <- xtabs(~ Treatment+Improved, data=Arthritis)
mytable
# row sums and percentages
margin.table(mytable, 1)
prop.table(mytable, 1)
# column sums and percentages
margin.table(mytable, 2)
prop.table(mytable, 2)
# Cell Percentages
prop.table(mytable)
# Add marginal SUMs
addmargins(mytable)
addmargins(prop.table(mytable))
addmargins(prop.table(mytable, 1), 2)
addmargins(prop.table(mytable, 2), 1)
d <- as.data.frame(addmargins(mytable))
#########################################
### 2. Two-Way Tables Using CrossTable()
#########################################
# Two-way table using CrossTable (similar to SAS Proc Freq)
library(gmodels)
CrossTable(Arthritis$Treatment, Arthritis$Improved)
help(CrossTable)
#########################################
### 2. Multidimensional Contingency Table
#########################################
# xtabs()
mytable <- xtabs(~ Treatment+Sex+Improved, data=Arthritis)
mytable
# table()
with(Arthritis, table(Treatment,Sex,Improved))
# ftable()
ftable(mytable)
margin.table(mytable, 1)
margin.table(mytable, 2)
margin.table(mytable, 3)
margin.table(mytable, c(1,3))
ftable(prop.table(mytable, c(1, 2)))
ftable(addmargins(prop.table(mytable, c(1, 2)), 3))
ftable(addmargins(prop.table(mytable, c(1, 2)), 3)) * 100
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment