如何在用自定义函数添加p值后恢复R的模型摘要包中相关表的默认格式

x33g5p2x  于 2023-04-27  发布在  其他
关注(0)|答案(1)|浏览(81)

这是最近一篇关于如何将p值添加到相关性表的文章的后续问题。
How to add a p-value to a correlation table while using model summary package in r?
Vincent提出的解决方案(如下所示)是为method参数使用一个自定义函数。

library(modelsummary)
library(correlation)

dat = mtcars[1:5, 1:5]

fun = function(x) {
    out = correlation(x)
    stars = c("*" = .2, "**" = .15, "***" = .05)
    p = modelsummary:::make_stars(out$p, stars)
    out$r = sprintf("%.2f%s", out$r, p)
    out = as.matrix(out)
    return(out)
}

datasummary_correlation(dat, method = fun)

自定义函数解决了p值问题,但是我现在得到了一个完整的矩形相关表,显示所有值,而在添加自定义函数之前,我默认只得到了下三角形值(这是我想要的)。datasummary_correlation(dat)使用默认参数生成一个下三角形相关表(但它没有p值)。
下面链接的Modelsummary文档指出,在自定义函数中插入datasummary_correlation_format()将允许我恢复默认设置。
https://vincentarelbundock.github.io/modelsummary/reference/datasummary_correlation_format.html
但我不能让它工作。
以下是我的尝试

library(modelsummary)
library(correlation)

dat = mtcars[1:5, 1:5]

fun = function(x) {
    out = correlation(x)
  
 datasummary_correlation_format(
    out,
    fmt = 2,
    upper_triangle = ".",
    diagonal = "1")

    stars = c("*" = .2, "**" = .15, "***" = .05)
    p = modelsummary:::make_stars(out$p, stars)
    out$r = sprintf("%.2f%s", out$r, p)
    out = as.matrix(out)
    return(out)
}

datasummary_correlation(dat, method = fun)
gkl3eglg

gkl3eglg1#

尝试:

library(modelsummary)
library(correlation)

dat = mtcars[, 1:5]

fun = function(x) {
    out = correlation(x)
    stars = c("*" = .2, "**" = .15, "***" = .05)
    p = modelsummary:::make_stars(out$p, stars)
    out$r = sprintf("%.2f%s", out$r, p)
    out = as.matrix(out)
    out = datasummary_correlation_format(out, fmt = 2, upper_triangle = ".")
    return(out)
}

datasummary_correlation(dat, method = fun)
每加仑圆柱体分散马力德拉特
每加仑1....
圆柱体-0.85***1...
分散-0.85***0.90***1..
马力-0.78***0.83***0.79***1.
德拉特68***-.70***-.71***- 点45***1

相关问题