admin管理员组

文章数量:1279084

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:

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.

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:

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.

Share Improve this question asked Feb 25 at 9:22 robertspierrerobertspierre 4,4313 gold badges41 silver badges63 bronze badges 1
  • which is good practice from a data viz purist's perspective since this type of correlation is bounded to -1, ..., 1. In other words, 0. does not add information--in contrast it is "visually annoying" (probably not how to say it). Annoying are the .00 of 1... – Friede Commented Feb 25 at 10:14
Add a comment  | 

1 Answer 1

Reset to default 2

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

本文标签: rLeading zeros in datasummarycorrelationStack Overflow