This is a follow-up question to a recent post about how to add p-values to a correlation table.
How to add a p-value to a correlation table while using model summary package in r?
The solution proposed by Vincent (reproduced below) is to use a custom function for the method
argument.
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)
The custom function solves the p-value issue however I now get a full rectangular correlation table showing all values whereas before adding the custom function I got only the lower triangle values by default (which is what I want). datasummary_correlation(dat)
produces a lower-triangle correlation table using default arguments (but it doesn't have p-values).
Modelsummary documentation linked below indicates that inserting datasummary_correlation_format()
in the custom function will allow me to restore the default settings.
https://vincentarelbundock.github.io/modelsummary/reference/datasummary_correlation_format.html
But I can't get it to work.
Here is my attempt
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)
Try:
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)
mpg | cyl | disp | hp | drat | |
---|---|---|---|---|---|
mpg | 1 | . | . | . | . |
cyl | -.85*** | 1 | . | . | . |
disp | -.85*** | .90*** | 1 | . | . |
hp | -.78*** | .83*** | .79*** | 1 | . |
drat | .68*** | -.70*** | -.71*** | -.45*** | 1 |