Spearman
Spearman correlation test
corr.test function
update.packages() # update all installed R packages
install.packages('psych') # download and install
Spearman correlation test
# import 'psych' package
library(psych)
# generate a test data set (data.frame table)
x1 = sample(100:200,10)
x2 = sample(100:200,10)
x3 = sample(100:200,10)
y1 = sample(1000:2000,10)
y2 = sample(1000:2000,10) + 10*x1 # create correlation between x1 and y2
mydata = data.frame(x1,x2,x3,y1,y2)
rownames(mydata) <- letters[1:10]
mydata
x1 x2 x3 y1 y2
a 116 187 123 1741 2557
b 171 179 180 1128 2970
c 189 136 158 1898 3524
d 194 134 159 1683 3528
e 145 170 161 1498 2676
f 168 125 156 1078 3190
g 177 190 119 1360 2806
h 119 181 184 1032 2402
i 109 130 176 1605 2406
j 138 139 118 1460 2850
# Spearman correlation - pairwise between all columns of a table
spearman <- corr.test(mydata, method="spearman", adjust="none")
spearman$r # Correlation matrix
x1 x2 x3 y1 y2
x1 1.00000000 -0.09090909 -0.13939394 0.1272727 0.8545455
x2 -0.09090909 1.00000000 -0.09090909 -0.1393939 -0.4424242
x3 -0.13939394 -0.09090909 1.00000000 -0.2606061 -0.2848485
y1 0.12727273 -0.13939394 -0.26060606 1.0000000 0.2484848
y2 0.85454545 -0.44242424 -0.28484848 0.2484848 1.0000000
spearman$p # p-values (significant correlation < 0.05)
x1 x2 x3 y1 y2
x1 0.000000000 0.8027717 0.7009319 0.7260570 0.001636803
x2 0.802771731 0.0000000 0.8027717 0.7009319 0.200422687
x3 0.700931885 0.8027717 0.0000000 0.4670891 0.425038155
y1 0.726057015 0.7009319 0.4670891 0.0000000 0.488776305
y2 0.001636803 0.2004227 0.4250382 0.4887763 0.000000000
Correlation between two datasets
# Spearman correlation - only between columns of two different tables
# same, but data spitted into two tables
x = mydata[1:3]
y = mydata[4:5]
spearman <- corr.test(x, y, method="spearman", adjust="none")
spearman$r # Correlation matrix, only of x and y column-pairs
y1 y2
x1 0.1272727 0.8545455
x2 -0.1393939 -0.4424242
x3 -0.2606061 -0.2848485
spearman$p # p-values
y1 y2
x1 0.7260570 0.001636803
x2 0.7009319 0.200422687
x3 0.4670891 0.425038155
A p-value < 0.05 shows a strong evidence for a correlation between x and y.
Bonferroni correction for multiple comparison
# Spearman correlation - Bonferroni correction for multiple comparison
spearman <- corr.test(x, y, method="spearman", adjust="bonferroni")
spearman$r # Correlation matrix (same values)
y1 y2
x1 0.1272727 0.8545455
x2 -0.1393939 -0.4424242
x3 -0.2606061 -0.2848485
spearman$p # p-values (corrected/adjusted N*p)
y1 y2
x1 1 0.00982082
x2 1 1.00000000
x3 1 1.00000000
# alternative correction methods: "fdr", "bonferroni", "hochberg", "holm", "hommel", "BH", "BY", "none"
# install (if not already done)
update.packages() # update all installed R packages
install.packages('corrplot') # download and install
# plot correlations
library(corrplot)
corrplot(spearman$r, method = "circle")
# save as pdf
dev.copy(pdf, 'fig_corrplot.pdf', width = 6, height = 6)
dev.off()