Search code examples
rsweavecorrelation

Correlation matrix with p-values for xtable


I want to have correlation matrix with p-values for xtable to be use in Sweave. I tried this

library(ltm)
library(xtable)
mat <- matrix(rnorm(1000), 100, 10, dimnames = list(NULL, LETTERS[1:10]))
rcor.test(mat)
xtable(rcor.test(mat))

and it throws this error:

Error in UseMethod("xtable") : 
  no applicable method for 'xtable' applied to an object of class "rcor.test"

I wonder how to get the correlation matrix with p-values for xtable to be use in Sweave. Thanks in advance for your help.


Solution

  • To see what's going on I would always suggest saving the object of interest and then looking at its structure using str.

    library(ltm)
    library(xtable)
    mat <- matrix(rnorm(1000), 100, 10, dimnames = list(NULL, LETTERS[1:10]))
    out <- rcor.test(mat)
    str(out)
    

    and it looks like the table that is being printed isn't actually stored in here. So let's look at the print method for rcor.test

    getAnywhere(print.rcor.test)
    

    We see that that method actually constructs the matrix that gets printed out but doesn't return it. So to get the matrix so that we can use xtable from this we'll just... steal the code to construct that matrix. Instead of printing out the matrix and then returning the original object we'll return the constructed matrix.

    get.rcor.test.matrix <- function (x, digits = max(3, getOption("digits") - 4), ...) 
    {
        ### Modified from print.rcor.test
        mat <- x$cor.mat
        mat[lower.tri(mat)] <- x$p.values[, 3]
        mat[upper.tri(mat)] <- sprintf("%6.3f", as.numeric(mat[upper.tri(mat)]))
        mat[lower.tri(mat)] <- sprintf("%6.3f", as.numeric(mat[lower.tri(mat)]))
        ind <- mat[lower.tri(mat)] == paste(" 0.", paste(rep(0, digits), 
            collapse = ""), sep = "")
        mat[lower.tri(mat)][ind] <- "<0.001"
        ind <- mat[lower.tri(mat)] == paste(" 1.", paste(rep(0, digits), 
            collapse = ""), sep = "")
        mat[lower.tri(mat)][ind] <- ">0.999"
        diag(mat) <- " *****"
        cat("\n")
    
        ## Now for the modifications
        return(mat)
    
        ## and ignore the rest
        #print(noquote(mat))
        #cat("\nupper diagonal part contains correlation coefficient estimates", 
        #    "\nlower diagonal part contains corresponding p-values\n\n")
        #invisible(x)
    }
    

    Now let's get our matrix and use xtable on it.

    ourmatrix <- get.rcor.test.matrix(out)
    xtable(ourmatrix)