为了了解发生了什么,我建议始终保存感兴趣的对象,然后使用
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), ...)
{
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")
return(mat)
}
现在让我们获取矩阵并在其上使用xtable。
ourmatrix <- get.rcor.test.matrix(out)
xtable(ourmatrix)