How to change Pearson to Spearman rank correlation

As Andrés mentioned before, please, try to use 'reprex ' (FAQ ) in future. It's a cool tool to post your questions to the R-communtiy. It helps us to help you! :slight_smile:

Based on your first request a possible solution in a reprex :slight_smile:

library(PerformanceAnalytics)

data(managers)
head(managers[,1:4], n = 10)
#>               HAM1    HAM2    HAM3    HAM4
#> 1996-01-31  0.0074      NA  0.0349  0.0222
#> 1996-02-29  0.0193      NA  0.0351  0.0195
#> 1996-03-31  0.0155      NA  0.0258 -0.0098
#> 1996-04-30 -0.0091      NA  0.0449  0.0236
#> 1996-05-31  0.0076      NA  0.0353  0.0028
#> 1996-06-30 -0.0039      NA -0.0303 -0.0019
#> 1996-07-31 -0.0231      NA -0.0337 -0.0446
#> 1996-08-31  0.0395 -0.0001  0.0461  0.0351
#> 1996-09-30  0.0147  0.1002  0.0653  0.0757
#> 1996-10-31  0.0288  0.0338  0.0395 -0.0180

#modified function chart.Correlation2(...)
chart.Correlation2 <- function (R, histogram = TRUE, method = NULL, ...){
  x = checkData(R, method = "matrix")
  if (is.null(method)) #modified
    method = 'pearson'
  
  use.method <- method #added
  panel.cor <- function(x, y, digits = 2, prefix = "", use = "pairwise.complete.obs", 
                        method = use.method, cex.cor, ...) { #modified
    usr <- par("usr")
    on.exit(par(usr))
    par(usr = c(0, 1, 0, 1))
    r <- cor(x, y, use = use, method = method)
    txt <- format(c(r, 0.123456789), digits = digits)[1]
    txt <- paste(prefix, txt, sep = "")
    if (missing(cex.cor)) 
      cex <- 0.8/strwidth(txt)
    test <- cor.test(as.numeric(x), as.numeric(y), method = method)
    Signif <- symnum(test$p.value, corr = FALSE, na = FALSE, 
                     cutpoints = c(0, 0.001, 0.01, 0.05, 0.1, 1), symbols = c("***", 
                                                                              "**", "*", ".", " "))
    text(0.5, 0.5, txt, cex = cex * (abs(r) + 0.3)/1.3)
    text(0.8, 0.8, Signif, cex = cex, col = 2)
  }
  f <- function(t) {
    dnorm(t, mean = mean(x), sd = sd.xts(x))
  }
  dotargs <- list(...)
  dotargs$method <- NULL
  rm(method)
  hist.panel = function(x, ... = NULL) {
    par(new = TRUE)
    hist(x, col = "light gray", probability = TRUE, axes = FALSE, 
         main = "", breaks = "FD")
    lines(density(x, na.rm = TRUE), col = "red", lwd = 1)
    rug(x)
  }
  if (histogram) 
    pairs(x, gap = 0, lower.panel = panel.smooth, upper.panel = panel.cor, 
          diag.panel = hist.panel)
  else pairs(x, gap = 0, lower.panel = panel.smooth, upper.panel = panel.cor)
}

#if method option not set default is 'pearson'
chart.Correlation2(managers[,1:4], histogram=TRUE, pch="19")

chart.Correlation2(managers[,1:4], histogram=TRUE, pch="19", method = 'spearman')
#> Warning in cor.test.default(as.numeric(x), as.numeric(y), method = method):
#> Cannot compute exact p-value with ties

Created on 2019-03-15 by the reprex package (v0.2.1)

1 Like