问题
I've produced a comparison of correlation matrices using psych::cortest.mat. I'd like to put the output in a Sweave file for production with knitr. When I use the Hmisc::latex() function, it works, but it also produces about 7 digits for each result, which makes it really unattractive. I could just produce the output with the markup argument within knitr, but all the other tables in my document are more efficiently produced with latex output (results='asis') .
Thoughts?
#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='')
回答1:
The cor.comparison
object is of class 'psych' and 'cortest'. There is no print.cortest method but there is a print.psych method and it is HUGE. It' apparently designed to hadle all of hte different types of objects and it appears the the print method for cortest is this code:
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")
So you would probably be better off simply targetting the items in that object rather than trying to use a "shotgun" with 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"
So just round the chi2 and prob values:
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='')
来源:https://stackoverflow.com/questions/31712030/control-digits-printed-by-hmisclatex-on-a-psych-object