hughjonesd / huxtable

An R package to create styled tables in multiple output formats, with a friendly, modern interface.
http://hughjonesd.github.io/huxtable
Other
321 stars 28 forks source link

insert_row function alters inserted text #236

Closed longjp closed 1 year ago

longjp commented 1 year ago

The insert_row function may alter text in the insertion. I came across this problem when trying to convert gtsummary tables into huxtables. Thank you to @ddsjoberg for the MWE below. Note that we try to insert "stat_1 = "A, N = 1,003" but the number 1,3 appear (two 0's deleted).

packageVersion("huxtable")
#> [1] '5.5.2'

structure(
  list(label = "Variable", stat_1 = "502 (252, 752)", stat_2 = "1,008 (1,006, 1,011)"), 
  row.names = c(NA, -1L), 
  class = c("tbl_df", "tbl", "data.frame")
) |> 
  huxtable::as_huxtable(add_colnames = FALSE) |> 
  huxtable::insert_row(
    after = 0, 
    label = "**Characteristic**", 
    stat_1 = "**A**, N = 1,003", 
    stat_2 = "**B**, N = 10"
  )
#> Warning in knit_print.huxtable(x, ...): Unrecognized output format "gfm-yaml". Using `to_screen` to print huxtables.
#> Set options("huxtable.knitr_output_format") manually to "latex", "html", "rtf", "docx", "pptx", "md" or "screen".
       **Characteristic**   **A**, N = 1,3   **B**, N = 10         
       Variable             502 (252, 752)   1,008 (1,006, 1,011)  
hughjonesd commented 1 year ago

This looks to me very much like a number_format problem.

hughjonesd commented 1 year ago

Yes, indeed this is because the default number_format is being used. Just set number_format to NA for the first row. Huxtable's number recognition isn't perfect and here it is assuming that 1,003 is two numbers.

hughjonesd commented 1 year ago

The interesting question is why number_format is NA for the original huxtable, but is set to "%.3g" for the inserted row. The answer can be found in the "Automatic formatting" section of ?hux. One possible issue raised is that insert_row and similar functions might want to apply autoformat.

longjp commented 1 year ago

Thank you. That fixed it.