huxtable (version 4.6.1)

mapping-functions: How to set cell properties variably by cell contents

Description

This help page explains how to set properties differently for cells, depending on their contents.

Arguments

Value

The modified huxtable.

Caveat

Most functions convert the huxtable to a matrix using as.matrix(). This can have unexpected results if you mix character and numeric data. See the example.

Technical details

fn must be a function taking four arguments: the (entire) original huxtable ht, a numeric vector of rows, a numeric vector of cols, and the current property values for ht[rows, cols], as a matrix. It should return the new property values for ht[rows, cols], as a matrix.

Here's an example. Suppose we want to highlight cells of a correlation matrix with low p values:

  data(attitudes)
  att_corr <- psych::corr.test(attitudes)
  # att_corr has components r (correlations) and p (p values)

corr_hux <- as_hux(att_corr$r) by_p_value <- function (ht, rows, cols, current) { result <- current pvals <- att_corr$p[rows, cols] result[pvals < 0.01] <- "red" result[pvals < 0.05] <- "orange" result }

Details

For example, in a table of p-values, you could bold cells where p < 0.05:

  map_bold(pval_hux, by_ranges(0.05, c(TRUE, FALSE)))

Or you can use red text for a particular value:

  hxtbl %>% map_text_color(by_values("Warning" = "red"))

There is a map_xxx function for each huxtable cell property. The syntax is:

  map_xxx(ht, row, col, fn)

where xxx is the property name.

row and col specify ranges of rows and columns. See rowspecs for details. To set properties for the whole table, you can omit row and col:

  map_xxx(ht, fn)

The fn argument is a mapping function which maps cell contents to property values.

Examples

Run this code
# NOT RUN {
ht <- hux(c("OK", "Warning", "Error"))
ht <- map_text_color(ht, by_values(
        OK      = "green",
        Warning = "orange",
        Error   = "red"
      ))
ht

# Leaving NA values alone:
map_text_color(ht, by_values(
      "OK" = "blue", NA, ignore_na = TRUE))

# Resetting values:
map_text_color(ht, by_values(
      "OK" = "blue", NA, ignore_na = FALSE))

ht <- hux(rnorm(5), rnorm(5), rnorm(5))
map_background_color(ht, by_ranges(
        c(-1, 1),
        c("blue", "yellow", "red")
      ))
map_background_color(ht,
      by_equal_groups(2, c("red", "green")))

ht <- hux(
        Coef = c(3.5, 2.4, 1.3),
        Pval = c(0.04, 0.01, 0.07),
        add_colnames = TRUE
      )
map_bold(ht, everywhere, "Pval",
      by_ranges(0.05, c(TRUE, FALSE)))

# Problems with as.matrix:

ht <- hux(c(-1, 1, 2), letters[1:3])
as.matrix(ht)          # look at the spaces...
as.matrix(ht) > 0      # uh oh
map_text_color(ht,
      by_cases(. < 0 ~ "red", TRUE ~ "blue"))

# To avoid this, only look at the truly numeric columns:
map_text_color(ht, row = 1:3, col = 1,
      by_cases(. < 0 ~ "red", TRUE ~ "blue"))
# }

Run the code above in your browser using DataCamp Workspace