Spearman correlations can be produced with the corr.test()
function from the psych
package.
To illustrate use of Spearman correlation with ranked data, we’ll create two ranked variables for the Motor Trend Cars data set, mtcars
, install the psych
package, and then run corr.test()
.
install.packages("psych")
library(psych)
# create a couple of rank variables with mtcars data set
# sort & create rank for wt
mtcars <- mtcars[order(mtcars$wt),]
mtcars$rank_wt <- 1:nrow(mtcars)
# sort & create rank for qsec
mtcars <- mtcars[order(mtcars$qsec),]
mtcars$rank_qsec <- 1:nrow(mtcars)
result <- corr.test(mtcars$rank_wt,mtcars$rank_qsec,method = "spearman",
alpha = 0.05)
print(result, short = FALSE)
Output from the test looks like this:
> print(result, short = FALSE)
Call:corr.test(x = mtcars$rank_wt, y = mtcars$rank_qsec, method = "spearman",
alpha = 0.05)
Correlation matrix
[1] -0.22
Sample Size
[1] 32
Probability values adjusted for multiple tests.
[1] 0.23
Confidence intervals based upon normal theory. To get bootstrapped values, try cor.ci
raw.lower raw.r raw.upper raw.p lower.adj upper.adj
NA-NA -0.53 -0.22 0.14 0.23 -0.53 0.14
Next, we’ll run a Pearson correlation on the original data to compare results.
# compare with pearson R for continuous variables
result <- corr.test(mtcars$wt,mtcars$qsec,alpha = 0.05)
print(result, short = FALSE)
…and the output:
> print(result, short = FALSE)
Call:corr.test(x = mtcars$wt, y = mtcars$qsec, alpha = 0.05)
Correlation matrix
[1] -0.17
Sample Size
[1] 32
Probability values adjusted for multiple tests.
[1] 0.34
Confidence intervals based upon normal theory. To get bootstrapped values, try cor.ci
raw.lower raw.r raw.upper raw.p lower.adj upper.adj
NA-NA -0.49 -0.17 0.19 0.34 -0.49 0.19
The two techniques produce similar results. In the original data, wt
has a slight negative correlation with qsec
, but it is not signficantly different from zero at alpha = 0.05. The magnitude of the Spearman correlation is slightly larger than the Pearson correlation, but it’s still not significantly different from zero at alpha = 0.05.
Comparison to JASP
In the comments the OP asked why the statistics software JASP produces different results than R. When I installed JASP, loaded the mtcars
data with the rank columns I created, and ran Spearman’s rho, JASP produced the same results as R within rounding error.
8
solved I don’t know R and I want to calculate Spearman correlation in R with a given alpha and want to know the p value [closed]