Skip to content

Instantly share code, notes, and snippets.

@izamryan
Created July 28, 2013 08:25
Show Gist options
  • Save izamryan/6097934 to your computer and use it in GitHub Desktop.
Save izamryan/6097934 to your computer and use it in GitHub Desktop.
Calculating covariance and correlation with #rstats
options(digits=4)
# Definitions
Table1 = matrix(data=c(1/8,0,2/8,1/8,1/8,2/8,0,1/8),nrow=4,ncol=2,byrow=T)
Table1
X=c(0,1,2,3)
Y=c(0,1)
X1=c(0,0,1,1,2,2,3,3)
Y1=c(0,1,0,1,0,1,0,1)
Table2 <- data.frame (X1,Y1)
# 3.2 - Bivariate discrete distributions
Pr.x = matrix(data=rowSums(Table1),nrow=4)
Pr.x
E.x=sum(Pr.x * X) ## E[X], marginal probability of X
E.x
# Marginal PDFs
Pr.y = matrix(data=colSums(Table1),ncol=2)
Pr.y
E.y=sum(Pr.y * Y) ## E[Y], marginal probability of Y
E.y
# Variance and SD
Var.x=sum(X**2*Pr.x)-E.x**2Var.x
SD.x=sqrt(Var.x)SD.x
Var.y=sum(Y**2*Pr.y)-E.y**2Var.y
SD.y=sqrt(Var.y)SD.y
# Covariance
Table2$Pr.xy <- c(t(Table1))
Table2$stdX <- Table2[["X1"]] - E.x
Table2$stdY <- Table2[["Y1"]] - E.y
Table2$stdXstdY <- Table2[["stdX"]] * Table2[["stdY"]]
Table2$PrWeight <- Table2[["Pr.xy"]] * Table2[["stdXstdY"]]
cov.xy=sum(Table2[["PrWeight"]])cov.xy
# Correlation
corr.xy=cov.xy / (SD.x * SD.y)corr.xy
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment