2012-05-25 43 views
4

我想要在Sweave中使用xtable的p值的相关矩阵。我想这xtable的p值的相关矩阵

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

,并抛出这个错误:

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

我不知道怎么去用p值的相关性矩阵xtable是在Sweave使用。在此先感谢您的帮助。

+0

在一个侧面说明 - 我建议检查出knitr。它基本上是Sweave,但很多*使用更好。 – Dason

+0

感谢@Dason为您的好建议。 – MYaseen208

回答

6

要看看发生了什么我总是建议保存感兴趣的对象,然后使用str来查看其结构。

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

它看起来好像正在打印的表格实际上并没有存储在这里。所以,让我们来看看在打印方法rcor.test

getAnywhere(print.rcor.test) 

我们可以看到,该方法实际上构造了被打印出来,但不会返回它的基质。所以要得到矩阵,以便我们可以使用xtable,我们只需要...窃取代码来构造矩阵。不是打印矩阵然后返回原始对象,而是返回构造的矩阵。

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) 
} 

现在让我们来得到我们的矩阵,并使用它的xtable。你

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

真棒@Dason。非常感谢你的帮助。非常感激。 – MYaseen208

+2

+1对于你如何来解决问题的很好的解释。 –

1

也可以用自己的功能是这样的:

mat <- matrix(rnorm(1000), nrow = 100, ncol = 10, 
       dimnames = list(NULL, LETTERS[1:10])) 
cor_mat <- function(x, method = c("pearson", "kendall", "spearman"), 
        alternative = c("two.sided", "less", "greater")) { 
    stopifnot(is.matrix(x) || is.data.frame(x)) 
    stopifnot(ncol(x) > 1L) 
    if (is.data.frame(x)) x <- data.matrix(x) 
    alternative <- match.arg(alternative) 
    method <- match.arg(method) 
    n <- ncol(x) 
    idx <- combn(n, 2L) 
    p.vals <- numeric(ncol(idx)) 
    for (i in seq_along(p.vals)) { 
     p.vals[i] <- cor.test(x = x[, idx[1L, i]], y = x[, idx[2L, i]], 
           method = method, alternative = alternative)$p.value 
    } 
    res <- matrix(NA, ncol = n, nrow = n) 
    res[lower.tri(res)] <- p.vals 
    return(res) 
} 
library(xtable) 
xtable(cor_mat(mat))