### Class examples from Week 8: Correlations ### Ken Benoit Mar 2010 ## Height and Weight example from L&F p233- # define the data from p233 child <- LETTERS[1:8] x <- c(49, 50, 53, 55, 60, 55, 60, 50) y <- c(81, 88, 87, 99, 91, 89, 95, 90) # scatterplots from p244 plot(x, y, xlab="Height in inches", ylab="Weight in pounds", pch=19) text(x, y, child, pos=4) # add mean lines abline(v=mean(x), h=mean(y), lty="dashed") ## computations from p245 xminusxbar <- x - mean(x) yminusybar <- y - mean(y) devproduct <- xminusxbar * yminusybar data.frame(child=child, X=x, Y=y, xminusxbar, yminusybar, devproduct) (SP <- sum(devproduct)) xminusxbar2 <- xminusxbar^2 yminusybar2 <- yminusybar^2 (SSx <- sum(xminusxbar2)) (SSy <- sum(yminusybar2)) data.frame(child=child, X=x, Y=y, xminusxbar, yminusybar, devproduct, xminusxbar2, yminusybar2) ## define function to compute r from p246 pearsonr <- function(x, y) { xdev <- x - mean(x) ydev <- y - mean(y) sum(xdev*ydev) / sqrt(sum(xdev^2)*sum(ydev^2)) } pearsonr(x,y) pearsonrcomp <- function(x, y) { N <- length(x) (sum(x*y) - N*mean(x)*mean(y)) / sqrt((sum(x^2)-N*mean(x)^2) * (sum(y^2)-N*mean(y)^2)) } pearsonrcomp(x,y) ## Example L&F p247 x <- c(12,10,6,16,8,9,12,11) y <- c(12,8,12,11,10,8,16,15) # using our created function pearsonr(x,y) # using R's built-in correlation command cor(x,y) # compute the empirical t-value (t.calc <- (.24*sqrt(8-2) / sqrt(1-.24^2))) # compute the critical t-value (t.crit <- qt(1-.05/2, 6)) # compare t.calc > t.crit # using R's built-in correlation significance test cor.test(x,y) ## Final example from L&F from pp249-251 x <- c(10,3,12,11,6,8,14,9,10,2) y <- c(1,7,2,3,5,4,1,2,3,10) cor.test(x,y) # make a picture of it plot(x,y,pch=19) respondent <- LETTERS[1:10] text(x,y,respondent,pos=4) abline(v=mean(x), lty="dashed") abline(h=mean(y), lty="dashed") abline(lm(y~x)) # "regression" line