相关矩阵及其p值的xtable

4

我希望能够使用 xtable 生成相关系数矩阵并附带p值,以便在 Sweave 中使用。我尝试了以下代码:

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"

我想知道如何使用xtableSweave中得到相关矩阵和p值。感谢您的帮助。


顺便提一下 - 我建议你去看看knitr。它基本上就是Sweave,但使用起来要好得多。 - Dason
2个回答

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)

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接