我使用psych :: cortest.mat生成了相关矩阵的比较。我想将输出放在Sweave文件中以便用knitr进行生产。当我使用Hmisc :: latex()函数时,它可以工作,但它也为每个结果产生大约7位数,这使它真的没有吸引力。我可以使用knitr中的标记参数生成输出,但是使用latex输出(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='')
答案 0 :(得分:1)
cor.comparison
对象属于班级&#39; psych&#39;和&#39; cortest&#39;。没有print.cortest方法,但有一个print.psych方法,它是巨大的。它&#39;显然设计用于捕获所有不同类型的对象,看起来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")
所以你可能最好只是简单地定位该对象中的项目而不是尝试使用&#34;霰弹枪&#34;与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='')