Search code examples
rcorrelationp-value

R function to obtain Kendall's tau p-value with covariates?


I have two variables and a third covariate adjustor. How can I get an adjusted Kendall tau estimate plus one p-value?

a <- c(1.07, 1.9, -0.603, -0.391, -0.416, -0.376, -0.367, -0.296, 1.44, -0.698) 
b <- c(1.13, 1.95, 0.37, 0.404, -0.385, 0.168, -0.349, 0.481, 2.2, -0.687)
c <- c(3.75, 3.75, 3.74, 3.75, 3.75, 3.74, 3.74, 5.37, 8.18, 8.18)

I wish to get similar output to cor.test(a, b, method = "kendall") which has been adjusted for c.


Solution

  • Here is a function pcor_test to run a partial correlations test. The function is based on function pcor, package ppcor.
    The main difference between the contributed package's function and the function below is that pcor_test outputs an object of class "htest", as asked in the question.

    pcor_test <- function (x, y, z, method = c("pearson", "kendall", "spearman"), conf.level = 0.95, ...) {
      d1 <- deparse(substitute(x))
      d2 <- deparse(substitute(y))
      d3 <- deparse(substitute(z))
      data.name <- paste0(d1, " and ", d2, "; controlling: ", d3)
      method <- match.arg(method)
      Method <- paste0("Partial correlation test (", method, ")")
      alternative <- "true partial correlation is not equal to 0"
      
      pc <- ppcor::pcor.test(x, y, z, method = method)
    
      ht <- list(
        statistic = c(Stat = pc$statistic),
        parameter = c(n = pc$n, gp = pc$gp),
        p.value = pc$p.value,
        estimate = c(partial.cor = pc$estimate),
        alternative = alternative,
        method = Method,
        data.name = data.name
      )
      class(ht) <- "htest"
      ht
    }
    
    a <- c(1.07, 1.9, -0.603, -0.391, -0.416, -0.376, -0.367, -0.296, 1.44, -0.698) 
    b <- c(1.13, 1.95, 0.37, 0.404, -0.385, 0.168, -0.349, 0.481, 2.2, -0.687)
    c <- c(3.75, 3.75, 3.74, 3.75, 3.75, 3.74, 3.74, 5.37, 8.18, 8.18)
    
    pcor_test(a, b, c, method = "kendall")
    #> 
    #>  Partial correlation test (kendall)
    #> 
    #> data:  a and b; controlling: c
    #> Stat = 2.5651, n = 10, gp = 1, p-value = 0.01032
    #> alternative hypothesis: true partial correlation is not equal to 0
    #> sample estimates:
    #> partial.cor 
    #>   0.6834271
    
    ppcor::pcor.test(a, b, c, method = "kendall")
    #>    estimate    p.value statistic  n gp  Method
    #> 1 0.6834271 0.01031523  2.565079 10  1 kendall
    

    Created on 2024-04-19 with reprex v2.1.0