huxtable R Package

repository·master·Indexed 43 days ago

https://github.com/hughjonesd/huxtable

An R package for creating sophisticated, styled tables for HTML, LaTeX, Word, PDF, Excel, and PowerPoint. It features a modern interface with dplyr compatibility, granular cell-level control over styling, and specialized functions like huxreg() for creating regression tables. Huxtable integrates with rmarkdown and quarto, providing a functional design pattern where separate functions modify specific table aspects.

Tokens
69.1K
Snippets
294
Records
417
Agent score
54%

What's inside huxtable

  1. Overview of Huxtable

    master

    Huxtable is an R package designed for creating highly styled tables across multiple output formats using a modern, friendly interface. It allows for granular control over text styling, number formatting, background colors, borders, padding, and alignment.

    Key capabilities include:

    • Cell Spanning: Support for cells spanning multiple rows and/or columns.
    • Data Manipulation: Integration with dplyr functions for table manipulation.
    • Document Integration: Automatic formatting for rmarkdown and quarto documents.
    • Regression Tables: The huxreg() function provides quick creation of regression tables.
    • Multi-format Output:
      • HTML, LaTeX, RTF, Microsoft Word, Excel, and PowerPoint (via officer and openxlsx).
      • PDF, PNG, and SVG (via typst).
    • Console Display: Formatted table display in the R console including borders, color, and text styles.
  2. Key features in huxtable 0.2.0

    master

    Version 0.2.0 introduced several core capabilities:

    • huxreg: A new function to convert a list of models into a huxtable.
    • Enhanced set_* Interface: Allows for column ranges, expressions (similar to subset), and filling values by row.
    • Cell Manipulation:
      • set_cell_properties: Set multiple properties on cells simultaneously.
      • Selection helpers: evens, odds, everywhere, every(n, from), final(n), and where(cond) for selecting rows, columns, and cells.
    • dplyr Integration: Supports dplyr verbs like filter and select directly on huxtables.
    • Exporting: Support for exporting to Word and PowerPoint via ReporteRs.
  3. Rotate text within cells

    master

    You can rotate the text within huxtable cells using degrees of anti-clockwise rotation.

    Rotation Values:

    • 0: Default (no rotation).
    • 90: Rotates text upwards (suitable for left-to-right languages).
    • 270: Rotates text downwards.
    • NA: Resets the rotation to the default of 0.

    Note on Layout: When rotating text, you will likely need to explicitly set col_width() and row_height() to ensure the table renders correctly in HTML or LaTeX.

    rotation(jams) <- 90
  4. Set cell properties variably by cell contents

    master

    You can set cell properties (like bolding, text color, or background color) differently for cells based on their values using map_... functions.

    There is a map_... function for each huxtable cell property (e.g., map_bold, map_text_color, map_background_color).

    Syntax

    map_property(ht, row, col, fn)

    • ht: The huxtable.
    • row and col: Ranges of rows and columns (use everywhere or rowspecs to target specific areas). Omit them to apply to the whole table.
    • fn: A mapping function that determines the property value based on cell contents.

    Available Mapping Functions

    Use these functions as the fn argument to define how properties are applied:

    • by_values(): For specific cell contents.
    • by_ranges(): For cells within numeric ranges.
    • by_quantiles() or by_equal_groups(): For cells based on quantiles or equal-sized groups.
    • by_regex(): For cells matching a string or regular expression.
    • by_colorspace(): To map numeric values to a colorspace.
    • by_rows() / by_cols(): To set properties in stripes.
    • by_function() / by_cases(): For general logic or conditional mapping.
    # Example: Bold cells where p < 0.05
    map_bold(pval_hux, by_ranges(0.05, c(TRUE, FALSE)))
    
    # Example: Red text for a specific value
    hxtbl %>% map_text_color(by_values("Warning" = "red"))
  5. Use `fmt_` functions with `number_format()`

    master
    The fmt_ functions in Huxtable are specialized utility functions designed to generate configuration objects for use with number_format(). Instead of manually constructing complex formatting objects, you can use these functions to create a Value object that defines how numbers should be displayed (e.g., decimal places, separators, etc.).
  6. Set border styles in huxtable

    master

    You can set the border style for the left, right, top, or bottom edges of a huxtable using getter/setter functions or specific set_* and map_* functions.

    Supported Styles:

    • "solid" (default)
    • "double"
    • "dashed"
    • "dotted"

    To reset a border style to the default ("solid"), set the value to NA.

    Important Concept: Collapsed Borders Borders in huxtable are "collapsed". This means the right border of one cell is the same as the left border of the adjacent cell. For example, right_border_style(ht)[, 1] is identical to left_border_style(ht)[, 2]. Setting one automatically updates the other.

    # Using getter/setter syntax
    left_border_style(ht) <- "dashed"
    
    # Using specific set functions
    set_top_border_style(ht, row, col, "dotted")
    
    # Using mapping functions for conditional styles
    map_bottom_border_style(ht, row, col, fn)
  7. Use generics from other packages

    master

    Huxtable re-exports certain generic functions from other R packages to provide a unified interface. These functions are used to handle different object classes consistently.

    Specifically, Huxtable provides access to:

    • glance: Part of the glance package.
    • tidy: Part of the tidy package.

    For detailed documentation on how to use these specific functions, refer to their respective package documentation.

  8. Restack tables to fit dimensions

    master

    If a table is too wide or too long, you can reorganize its layout using restacking functions. These functions automatically handle header rows if they are marked as headers.

    • restack_across(rows = n): Reorganizes the table to fit into fewer rows and more columns (makes the table taller/narrower).
    • restack_down(cols = n): Reorganizes the table to fit into more rows and fewer columns (makes the table wider/shorter).
    # Example: Restacking a table to be wider (fewer rows)
    iris_hux_wide <- iris_hux |> 
          set_header_rows(1:2, TRUE) |> 
          restack_across(rows = 7)
    
    # Example: Restacking a table to be taller (fewer columns)
    lego_hux |> restack_down(cols = 2)
  9. Wrap cell content over multiple lines

    master

    To enable text wrapping in a huxtable, you must first set a table width(). Text wrapping is controlled by the wrap property. If you want to insert newlines in cells, set a value for width() and set wrap to TRUE.

    long_text <- paste(rep("Some long text.", 10), collapse = " ")
    ht <- huxtable(Long = long_text)
    width(ht) <- 0.2
    wrap(ht) <- TRUE
  10. The Huxtable rendering pipeline

    master

    The rendering process follows a specific pipeline to ensure data is correctly presented in the target format:

    1. Content Cleaning: Before rendering, clean_contents() is called to apply number formatting, markdown rendering, escaping, and alignment based on the specific cell attributes and the intended output type.
    2. Format Assembly: The cleaned content is then passed to format-specific renderers:
      • HTML: to_html() assembles the table by building the <table> tag, caption, column widths, cell markup, and row wrappers.
      • LaTeX: to_latex() constructs the tabular section and wraps it in a floating environment with appropriate captions, size adjustments, and border/padding commands.
  11. Configure LaTeX output behavior in huxtable 5.0.0

    master

    In version 5.0.0, several changes were made to how LaTeX tables are rendered:

    • Padding: LaTeX \tabcolsep is now set to 0. Left and right padding now take effect even when wrap = FALSE.
    • Environments: The default LaTeX table environment is tabular unless width is set. If width is set, it uses tabularx.
    • Wrapping: The wrap argument only affects output if width is set; otherwise, cell wrapping is disabled.
    • Centering: Tables are centered using the \centerbox macro from the LaTeX adjustbox package. You may need to update your LaTeX adjustbox package to a recent version. You can check dependencies using check_latex_dependencies().
  12. Manage header rows and columns

    master

    Huxtable introduces the concept of header rows and columns. By default, data frame column names are treated as headers.

    To designate specific rows as headers, use set_header_rows(ht, row_numbers, TRUE). For columns, use header_cols() or set_header_cols().

    You can style these headers using style_headers(), style_header_cols(), or style_header_rows(). In themes, setting header_row/col = TRUE will automatically treat the first row/column as a header and apply header styling.

    # Set specific rows as headers
    set_header_rows(ht, row_numbers, TRUE)
    
    # Style headers
    style_headers(ht, bold = TRUE)