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"

xtableで使用するためのp値を持つ相関行列を取得する方法を知りたいSweaveです。よろしくお願いします。

4

2 に答える 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のprintメソッドを見てみましょう。

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)
于 2012-05-25T22:24:51.557 に答える
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))
于 2013-01-01T10:50:50.557 に答える