我想要在 Sweave
中使用 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"
我想知道如何为 xtable
获取具有 p 值的相关矩阵,以便在 Sweave
中使用。预先感谢您的帮助。
最佳答案
要了解发生了什么,我总是建议保存感兴趣的对象,然后使用 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)
关于r - xtable 与 p 值的相关矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10761923/