Skip to content

Instantly share code, notes, and snippets.

@geofferyzh
Created May 23, 2012 19:26
Show Gist options
  • Save geofferyzh/2777234 to your computer and use it in GitHub Desktop.
Save geofferyzh/2777234 to your computer and use it in GitHub Desktop.
RinAction - Basic Statistics - Association & Correlations
########################################################
########################################################
# -------- Test of independence & Association -------- #
########################################################
########################################################
##########################
# Evidence of Independence
##########################
# X-square
library(vcd)
mytable <- xtabs(~Treatment+Improved, data=Arthritis)
chisq.test(mytable)
mytable <- xtabs(~Improved+Sex, data=Arthritis)
chisq.test(mytable)
# Fisher's exact test
mytable <- xtabs(~Treatment+Improved, data=Arthritis)
fisher.test(mytable)
# Chochran-Mantel-Haenszel test
mytable <- xtabs(~Treatment+Improved+Sex, data=Arthritis)
mantelhaen.test(mytable)
##########################
# Strength of Association
##########################
library(vcd)
mytable <- xtabs(~Treatment+Improved, data=Arthritis)
assocstats(mytable)
########################################################
########################################################
# -------- Correlations -------- #
########################################################
########################################################
##############################
# Covariances and correlations
##############################
# 1. Square matrix
states <- state.x77[, 1:6]
cov(states)
cor(states)
cor(states, method="spearman")
cor(states, use="all.obs", method='pearson') # assumes no missing data, missing will produce an error
cor(states, use="everything", method='pearson') # any correlation involving a case with missing is set to missing
cor(states, use="complete.obs", method='pearson') # listwise deletion
cor(states, use="pairwise.complete.obs", method='pearson') # pairwise deletion
# 2. Nonsquare matrix
x <- states[, c("Population", "Income", "Illiteracy", "HS Grad")]
y <- states[, c("Life Exp", "Murder")]
cor(x, y)
######################
# Partial Correlations
######################
#partial correlation of population and murder rate, controlling
# for income, illiteracy rate, and HS graduation rate
install.packages("ggm")
library(ggm)
pcor(c(1, 5, 2, 3, 6), cov(states))
#######################################
# Testing correlations for significance
#######################################
# 1. Testing one correlation at a time
cor.test(states[, 3], states[, 5])
# 2. Correlation matrix and tests of significance via corr.test
library(psych)
corr.test(states, use = "complete")
corr.test(states, use = "pairwise")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment