Skip to content

Instantly share code, notes, and snippets.

@dantalus
Last active March 22, 2016 12:15
Show Gist options
  • Save dantalus/c716ed0573214233be63 to your computer and use it in GitHub Desktop.
Save dantalus/c716ed0573214233be63 to your computer and use it in GitHub Desktop.
# Returns a correlation coefficient, rounded, with any trailing zeros printed
corr <- function(x, y, ...){
as.numeric(formatC(round(cor(x = x, y = y,
use = "pairwise.complete.obs"), 2),
format = "f", 2))
}
# Generate the matrix of correlation coefficients. In this example, I want to
# correlate a set of variables (A:F) with one other variable (G), rather than
# the more common matrix of A:G with A:G.
library(dplyr)
corr.matrix <- data %>%
group_by(group) %>%
summarise(A = corr(A, G),
B = corr(B, G),
C = corr(C, G),
D = corr(D, G),
E = corr(E, G),
F = corr(F, G))
new.row.names <- corr.matrix[, 1]
corr.matrix <- corr.matrix[, -1]
rownames(corr.matrix) <- new.row.names
corr.matrix <- as.matrix(corr.matrix)
# Generate the matrix of p-values for the correlation coefficients
p.matrix <- data %>%
group_by(group) %>%
summarise(A = cor.test(A, G)$p.value,
B = cor.test(B, G)$p.value,
C = cor.test(C, G)$p.value,
D = cor.test(D, G)$p.value,
E = cor.test(E, G)$p.value,
F = cor.test(F, G)$p.value)
p.matrix <- p.matrix[, -1]
rownames(p.matrix) <- new.row.names
p.matrix <- as.matrix(p.matrix)
# Make the plot
library(corrplot)
corrplot(corr.matrix, method = "color",
addCoef.col = "black",
tl.col = "black", tl.srt = 45,
p.mat = p.matrix, sig.level = 0.2, insig = "blank")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment