rformattingmodelsummary

Leading zeros in datasummary_correlation


I don't understand why datasummary_correlation is removing leading zeros.

Here is an example:

library(correlation)
library(modelsummary)
library(tidyverse)

fun <- function(x) {
  out <- x |>
    correlation() |>
    summary(redundant = TRUE) |>
    format(digits=2)  |>
    as.matrix()
  row.names(out) <- out[, 1]
  out <- out[, 2:ncol(out)]
  lt <- upper.tri(out)
  out[lt] <- ""
  diag(out) <- rep("1.00", nrow(out))
  return(out)
}

datasummary_correlation(
  mtcars %>% select(mpg, cyl, disp),
  method = fun)

Which leads to:

enter image description here

For instance,for the correlation between mpg and cyl, I want to display -0.85***, not -.85***.

fun seems to return the table correctly formatted, so something within datasummary_correlation must be removing the leading zeros.


Solution

  • This vignette describes using datasummary_correlation_format which has an option leading_zero. Just getting the HTML table output was not so straight forward, because datasummary_correlation(dat, method = cor_fun) deletes the leading zeros again. So I opted for kableExtra to do the HTML conversion.

    Code

    library(correlation)
    library(modelsummary)
    library(tidyverse)
    
    fun <- function(x) {
      out <- x |>
        correlation() |>
        summary(redundant = TRUE) |>
        format(digits=2)  |>
        as.matrix()
      row.names(out) <- out[, 1]
      out <- out[, 2:ncol(out)]
      
      datasummary_correlation_format(
        out,
        fmt = 2,
        leading_zero = TRUE,
        upper_triangle = "",
        diagonal = "1.00")
    }
    
    library(kableExtra)
    
    kable(fun(mtcars %>% select(mpg, cyl, disp)), format = "html") %>%
      kable_styling(bootstrap_options = c("striped", "hover"))
    

    giving

    out