这是最近一篇关于如何将 p 值添加到相关表的帖子的后续问题。
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)
尝试:
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 | . | . | . | . |
圆柱 | -.85*** | 1 | . | . | . |
显示 | -.85*** | .90*** | 1 | . | . |
马力 | -.78*** | .83*** | .79*** | 1 | . |
讨厌 | .68*** | -.70*** | -.71*** | -.45*** | 1 |