1

我使用 psych::cortest.mat 对相关矩阵进行了比较。我想将输出放在 Sweave 文件中,以便使用 knitr 进行生产。当我使用 Hmisc::latex() 函数时,它可以工作,但它也会为每个结果产生大约 7 位数字,这使得它真的没有吸引力。我可以在 knitr 中使用 markup 参数生成输出,但我文档中的所有其他表都可以使用 latex output (results='asis') 更有效地生成。

想法?

#Sample data
variable1<-rnorm(100, mean=7, sd=1)
variable2<-rnorm(100, mean=4, sd=1)
variable3<-rnorm(100, mean=6, sd=1)
variable4<-rnorm(100, mean=8, sd=2)
variable5<-rnorm(100, mean=9, sd=1)
variable6<-rnorm(100, mean=7, sd=3)
#Correlation matrices
cor.mat1<-cor(data.frame(variable1, variable2, variable3))
cor.mat2<-cor(data.frame(variable4, variable5, variable6))
library(psych)
library(Hmisc)
#Compare matrices
cor.comparison<-cortest.mat(cor.mat1, cor.mat2, n1=100, n2=100)
#try to print
latex(cor.comparison, file='')
#try unclassing
test<-unclass(cor.comparison)
#Try with lapply
lapply(test, function(x) round(x,2))
#try also changing options(digits=)
options(digits=3)
latex(cor.comparison, file='')
4

1 回答 1

1

cor.comparison对象属于“心理”和“最核心”类。没有 print.cortest 方法,但有一种 print.psych 方法,而且非常大。它显然旨在处理所有不同类型的对象,并且似乎 cortest 的打印方法是以下代码:

 cortest = {
    cat("Tests of correlation matrices \n")
    cat("Call:")
    print(x$Call)
    cat(" Chi Square value", round(x$chi, digits), " with df = ", 
        x$df, "  with probability <", signif(x$p, digits), 
        "\n")
    if (!is.null(x$z)) cat("z of differences = ", round(x$z, 
        digits), "\n")

因此,您最好简单地瞄准该对象中的项目,而不是尝试使用带有 lapply 的“霰弹枪”。

> str(cor.comparison)
List of 5
 $ chi2 : num 8.68
 $ prob : num 0.192
 $ df   : num 6
 $ n.obs: num 100
 $ Call : language cortest.mat(R1 = cor.mat1, R2 = cor.mat2, n1 = 100, n2 = 100)
 - attr(*, "class")= chr [1:2] "psych" "cortest"

所以只需四舍五入 chi2 和 prob 值:

cor.comparison<-cortest.mat(cor.mat1, cor.mat2, n1=100, n2=100)
cor.comparison[c('chi2', 'prob')] <- lapply( cor.comparison[c('chi2', 'prob')], round, 2)
latex(cor.comparison, file='')
于 2015-07-29T22:40:36.583 回答