2012-05-25 45 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))