【问题标题】:control digits printed by Hmisc::latex on a psych objectHmisc::latex 在 psych 对象上打印的控制数字
【发布时间】:2015-07-29 22:06:22
【问题描述】:

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

【问题讨论】:

  • 如果您在测试中四舍五入列,那么为什么要将 cor.comparison 发送到 LaTeX?

标签: r latex psych hmisc


【解决方案1】:

cor.comparison 对象属于“psych”和“cortest”类。没有 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='')

【讨论】:

    猜你喜欢
    • 2012-09-06
    • 2013-01-24
    • 2019-02-11
    • 2018-03-27
    • 2017-12-15
    • 1970-01-01
    • 2017-04-16
    • 2023-02-04
    • 1970-01-01
    相关资源
    最近更新 更多