Example R programs and commands 18. Partial correlation coefficients # All lines preceded by the "#" character are my comments. # All other left-justified lines are my input. # All other indented lines are the R program output. # Read the data - TRANSPOSED # Y X1 X2 X3 X4 # -------------------------------------------------- data<-scan() 51.4 0.2 17.8 24.6 18.9 72.0 1.9 29.4 20.7 8.0 53.2 0.2 17.0 18.5 22.6 98.3 9.6 35.6 10.6 5.6 74.8 6.3 28.2 8.8 13.1 92.2 10.8 34.7 11.9 5.9 97.9 9.6 35.8 10.8 5.5 88.1 10.5 29.6 11.7 7.8 62.8 0.4 22.3 26.5 14.3 81.6 2.3 37.9 20.0 0.5 dim(data)<-c(5,10) # coerce data into a matrix -- TRANSPOSED x <- t(data) # un-transpose the data to same form as table varnames <- c("y","x1","x2","x3","x4") # names of the variables dimnames(x)<-list(NULL, varnames) # label the columns (only) by variable r <- cor(x) # Simple correlation matrix for all 5 variables # View the simple correlation matrix, noting that # the rows and columns inherit variable name labels from cor(): r y x1 x2 x3 x4 y 1.0000000 0.8942124 0.9150668 -0.7502887 -0.8451857 x1 0.8942124 1.0000000 0.6804904 -0.8754808 -0.5783092 x2 0.9150668 0.6804904 1.0000000 -0.5708813 -0.9678866 x3 -0.7502887 -0.8754808 -0.5708813 1.0000000 0.3950981 x4 -0.8451857 -0.5783092 -0.9678866 0.3950981 1.0000000 # PARTIAL CORRELATION COEFFICIENT calculations: c <- solve(r) # inverse of the simple correlation matrix r dprime <- diag(c) # d' = diagonal part of c -- VECTOR d1 <- diag(1/sqrt(dprime)) # inverse of square root of d' # Partial correlation coefficients are the off-diagonal elements of: p <- - d1 %*% c %*% d1 # note the minus sign p [,1] [,2] [,3] [,4] [,5] [1,] -1.0000000 0.8519844 0.6334847 0.3750495 0.2973679 [2,] 0.8519844 -1.0000000 -0.7005274 -0.7172729 -0.4922659 [3,] 0.6334847 -0.7005274 -1.0000000 -0.7788338 -0.9147358 [4,] 0.3750495 -0.7172729 -0.7788338 -1.0000000 -0.7980659 [5,] 0.2973679 -0.4922659 -0.9147358 -0.7980659 -1.0000000 # Use labels to identify the correlation coefficients: dimnames(p)<-list(varnames,varnames) # label the rows and columns p # print the final result y x1 x2 x3 x4 y -1.0000000 0.8519844 0.6334847 0.3750495 0.2973679 x1 0.8519844 -1.0000000 -0.7005274 -0.7172729 -0.4922659 x2 0.6334847 -0.7005274 -1.0000000 -0.7788338 -0.9147358 x3 0.3750495 -0.7172729 -0.7788338 -1.0000000 -0.7980659 x4 0.2973679 -0.4922659 -0.9147358 -0.7980659 -1.0000000 # REMARK. # # The R function -cov2cor() (note the minus sign) performs the # right operations to yield partial correlation coefficients, # if it gets the inverse correlation matrix as input: # -cov2cor(solve(cor(x))) # partial correlation coefficients y x1 x2 x3 x4 y -1.0000000 0.8519844 0.6334847 0.3750495 0.2973679 x1 0.8519844 -1.0000000 -0.7005274 -0.7172729 -0.4922659 x2 0.6334847 -0.7005274 -1.0000000 -0.7788338 -0.9147358 x3 0.3750495 -0.7172729 -0.7788338 -1.0000000 -0.7980659 x4 0.2973679 -0.4922659 -0.9147358 -0.7980659 -1.0000000