Movatterモバイル変換


[0]ホーム

URL:


Type:Package
Title:Easily Create and Style Tables for LaTeX, HTML and Other Formats
Version:5.8.0
Author:David Hugh-Jones [aut, cre]
Maintainer:David Hugh-Jones <davidhughjones@gmail.com>
Description:Creates styled tables for data presentation. Export to HTML, LaTeX, RTF, 'Word', 'Excel', 'PowerPoint', 'typst', SVG and PNG. Simple, modern interface to manipulate borders, size, position, captions, colours, text styles and number formatting. Table cells can span multiple rows and/or columns. Includes a 'huxreg' function to create regression tables, and 'quick_*' one-liners to print tables to a new document.
License:MIT + file LICENSE
URL:https://hughjonesd.github.io/huxtable/
BugReports:https://github.com/hughjonesd/huxtable/issues
Imports:assertthat, base64enc, commonmark, fansi, generics, glue,htmltools, memoise, R6, rlang, stats, stringi, stringr (≥1.2.0), tidyselect, utils, xml2
Suggests:AER, bookdown, broom (≥ 0.5.1), broom.mixed, covr, crayon,devtools, dplyr (≥ 0.7.0), flextable (≥ 0.6.9), ftExtra (≥0.0.2), ggplot2, httr, knitr, lme4, lmtest, lintr, nlme, nnet,officer, openxlsx, psych, quarto, rmarkdown, sandwich, scales,styler, testthat, tibble, tinytex
SystemRequirements:LaTeX packages: adjustbox, array, calc, caption,colortbl, fontspec, graphicx, hhline, hyperref, multirow,siunitx, tabularx, threeparttable, ulem, wrapfig
VignetteBuilder:knitr
Encoding:UTF-8
LazyData:true
RoxygenNote:7.3.2
Depends:R (≥ 2.10)
Config/testthat/edition:3
NeedsCompilation:no
Packaged:2025-11-06 16:42:19 UTC; davidhugh-jones
Repository:CRAN
Date/Publication:2025-11-07 06:10:36 UTC

Quick introduction to huxtable

Description

Huxtable is a package for creating HTML and LaTeX tables. It provides similarfunctionality to xtable, with a simpler interface.

Quick start

To create a huxtable object, usehuxtable() oras_huxtable():

 library(huxtable) employees <- huxtable(         Names    = c("Hadley", "Yihui", "Dirk"),         Salaries = c(1e5, 1e5, 1e5),         add_colnames = TRUE       ) car_hux <- as_hux(mtcars)

You can then set properties which affect how the huxtable is displayed:

 # make the first row bold: bold(employees)[1, ] <- TRUE # change the font size everywhere: font_size(employees) <- 10

Or you can use a tidyverse style with the pipe operator:

library(magrittr)employees <- employees %>%      set_font_size(10) %>%      set_bold(1, everywhere, TRUE)

For more information, seethe website orread the vignette withvignette("huxtable").

Seehuxtable-FAQ for frequently asked questions, including ways to gethelp.

To report a bug, or suggest an enhancement, visitgithub.

Author(s)

Maintainer: David Hugh-Jonesdavidhughjones@gmail.com

See Also

Useful links:


Replace a subset of a brdr object

Description

Replace a subset of a brdr object

Usage

## S3 replacement method for class 'brdr'x[...] <- value

Arguments

x

Abrdr object.

...

Indices.

value

Abrdr() object, number or matrix.

Details

You probably don't need to call this directly. If you wantto access border thicknesses, do e.g.

l_borders <- brdr_thickness(left_border(ht))

which will give you a matrix of numbers.

Value

Abrdr() object.


Subset a huxtable

Description

Subset a huxtable

Usage

## S3 method for class 'huxtable'x[i, j, drop = FALSE]## S3 replacement method for class 'huxtable'x[i, j] <- value## S3 replacement method for class 'huxtable'x$name <- value## S3 replacement method for class 'huxtable'x[[i, j]] <- value

Arguments

x

A huxtable.

i

Rows to select.

j,name

Columns to select.

drop

Only included for compatibility with⁠[.data.frame⁠. Do not use.

value

A matrix, data frame, huxtable or similar object.

Value

[ returns a huxtable.$ and[[ return data from theunderlying data frame.

Replacing existing rows and columns

For the replacement function⁠[<-⁠, ifvalue is a huxtable, then itsproperties will be copied intox. Replacement functions⁠$<-⁠ and⁠[[<-⁠replace existing data without affecting any properties.

Adding new rows and columns

If new columns or rows are created, then properties will be copiedfrom the last column or row ofx, or fromvalue ifvalue is a huxtable.

These methods are stricter than their data frame equivalents in some places.You can't add new rows or column at a numeric location without specifying allintervening rows/columns. New values must have the appropriate dimensions(vectors will be interpreted appropriately).

Examples

jams[1:3, ]class(jams[1:3, ])jams[, 1]jams$Typeprices <- huxtable(c("Price", 1.70, 2.00, 2.20))number_format(prices) <- 2bold(prices) <- TRUEjams[, 2] <- pricesjamsdata(jams)jams$price <- c("Price", 1.70, 2.00, 2.20)jams

Add column or row names

Description

Add a first row of column names, or a first column of row names, to the huxtable.

Usage

add_colnames(ht, rowname = NULL, ...)add_rownames(ht, colname = "rownames", preserve_rownames = TRUE, ...)

Arguments

ht

A huxtable.

rowname

Optional row name for the new row of column names.

...

Arguments passed to methods.

colname

Column name for the new column of row names.

preserve_rownames

Preserve existing row names.

Details

Note thatadd_colnames will change the mode of all columns to character. Also note that it willmove your rows down by one: what was row 1 will now be row 2, and the column names will now be row 1.

add_colnames preserves column names.add_rownames only preserves them if asked to.

Value

The modified object.

Examples

ht <- huxtable(  First = rnorm(5),  Second = rnorm(5),  add_rownames = FALSE)add_rownames(ht)add_colnames(ht)# Out by 1:add_rownames(add_colnames(ht))# Better:add_colnames(add_rownames(ht))# Alternatively:add_colnames(add_rownames(ht, ""))

Add a row with a footnote

Description

This adds a single row at the bottom. The first cell contains the footnote; it spansall table columns and has an optional border above.

Usage

add_footnote(ht, text, border = 0.8, number_format = NA, ...)

Arguments

ht

A huxtable.

text

Text for the footnote.

border

Width of the footnote's top border. Set to 0 for no border, orNULL to leave the border unchanged.

number_format

Number format for the footnote cell.

...

Other properties, passed toset_cell_properties() for the footnote cell.

Value

The modified huxtable

Examples

jams <- add_footnote(  jams,  "* subject to availability")jams

Insert one huxtable into another

Description

These functions combine two huxtables or similar objects andreturn the result.

Usage

add_rows(x, y, after = nrow(x), copy_cell_props = TRUE)add_columns(x, y, after = ncol(x), copy_cell_props = TRUE)

Arguments

x,y

Huxtables or objects that can be converted by as_hux

after

Row or column after whichy is inserted. Can be 0.Can be a row or column name. The default addsy to theend ofx.

copy_cell_props

Logical. Passed torbind.huxtable() orcbind.huxtable().

Details

Arguments in... can includecopy_cell_props.

Value

A huxtable.

See Also

insert_row() andinsert_column(), which insertmultiple values into a single row.

Examples

ht <- hux("Gooseberry", 2.15)add_rows(jams, ht)add_rows(jams, ht, after = 1)mx <- matrix(  c(    "Sugar", "50%", "60%", "40%",    "Weight (g)", 300, 250, 300  ),  4, 2)add_columns(jams, mx)

Set the horizontal alignment of cell content

Description

Values may be "left", "center", "right",NA or a single character. Ifvalue is a single character (e.g. a decimal point), then the cell isaligned on this character.

Usage

align(ht)align(ht) <- valueset_align(ht, row, col, value)map_align(ht, row, col, fn)

Arguments

ht

A huxtable.

value

A character vector or matrix. Set toNA to reset to the default, which is"left".

row

A row specifier. Seerowspecs for details.

col

An optional column specifier.

fn

A mapping function. Seemapping-functions for details.

Aligning on a decimal point

To align cells on the decimal point, setalign to"." or any other singlecharacter (e.g."," in European languages).

By default, huxtable aligns these cells by padding with spaces. The mechanicsof this were improved for LaTeX in version 5.3.0, but are still not perfect.Using a fixed-width font may help.

Ifoptions("huxtable.latex_siunitx_align") is set toTRUE, then inLaTeX output, numbers in these cells will be surrounded by⁠\\tablenum{}⁠.See the siunitx documentation for more details. Note that this may haveother side-effects, for example1e3 becomes⁠1 x 10^3⁠.

To use non-default decimal points, set bothalign(ht) andnumber_format(). See the example.

Examples

numbers <- c(1, 1.5, 1.03, 10, 10.01)number_hux <- as_hux(matrix(numbers, 5, 5))number_format(number_hux) <- "%.4g"number_format(number_hux)[, 5] <- fmt_pretty(  decimal.mark = ",",  big.mark = "")number_hux <- map_align(  number_hux,  by_cols("left", "center", "right", ".", ","))alignments <- c(  "left",  "centre",  "right",  "decimal (.)",  "decimal (,)")number_hux <- rbind(  alignments,  number_hux)align(number_hux)number_hux

Convert a huxtable for Excel

Description

If theopenxlsx package is installed, Huxtables can be converted toopenxlsx::openxlsx() Worbook objects, for use in Excel documents.

Usage

as_Workbook(ht, ...)## S3 method for class 'huxtable'as_Workbook(  ht,  Workbook = NULL,  sheet = "Sheet 1",  write_caption = TRUE,  start_row = 1,  start_col = 1,  ...)

Arguments

ht

A huxtable.

...

Not used.

Workbook

An existingWorkbook object. By default, a new workbook will be created.

sheet

Name for the worksheet where the huxtable will be created. Theworksheet will be created if it doesn't exist already.

write_caption

IfTRUE, print any caption in the row above or below the table.

start_row,start_col

Number. Write data starting at the given row and column.

Details

Useopenxlsx::saveWorkbook() to save the resulting object to an Excel file.

Properties are supported with the following exceptions:

Huxtable tries to guess appropriate widths and height for rows and columns; numericwidth() andheight() are treated as scaling factors.

Contents are only stored as numbers if a whole column is "numeric", i.e. canbe converted byas.numeric()). Otherwise, they are stored as text.

Value

An object of classWorkbook.

Examples

wb <- as_Workbook(jams)## Not run: openxlsx::saveWorkbook(  wb,  "my-excel-file.xlsx")## End(Not run)# multiple sheets in a single workbook:wb <- openxlsx::createWorkbook()wb <- as_Workbook(jams,  Workbook = wb, sheet = "sheet1")wb <- as_Workbook(  hux("Another", "huxtable"),  Workbook = wb,  sheet = "sheet2")

Convert a huxtable for Word/Powerpoint

Description

Huxtables can be converted toflextable::flextable() objects, for use in Word and Powerpoint documents.

Usage

as_flextable(x, ...)## S3 method for class 'huxtable'as_flextable(x, colnames_to_header = FALSE, ...)

Arguments

x

A huxtable.

...

Not used.

colnames_to_header

Use huxtable column names as the header. IfFALSE, the flextablewill contain only a body and no header.

Details

With recent versions of "flextable" and Pandoc, huxtables can be automatically outputtedfrom rmarkdownword_document and/orpowerpoint_presentation documents. (Powerpointpresentations require pandoc version >= 2.4.0.)

Properties are supported, with the following exceptions:

Value

an object of class flextable.

Challenge

Try to sayas_flextable.huxtable ten times without pausing.

Examples

ht <- hux(a = 1:3, b = 1:3)ft <- as_flextable(ht)## Not run: my_doc <- officer::read_docx()my_doc <- flextable::body_add_flextable(  my_doc, ft)print(my_doc,  target =    "path/to/my_doc.docx")## End(Not run)

Convert objects to huxtables

Description

as_huxtable oras_hux converts an object to a huxtable.Conversion methods exist for data frames and tibbles, tables,ftables, matrices and (most) vectors.

Usage

as_huxtable(x, ...)as_hux(x, ...)## Default S3 method:as_huxtable(  x,  add_colnames = getOption("huxtable.add_colnames", TRUE),  add_rownames = FALSE,  autoformat = getOption("huxtable.autoformat", TRUE),  ...)## S3 method for class 'grouped_df'as_huxtable(x, ..., groups_to_headers = FALSE)is_huxtable(x)is_hux(x)

Arguments

x

Object to convert.

...

Arguments passed on tohuxtable().

add_colnames

IfTRUE, add a first row of column names to the huxtable.

add_rownames

IfTRUE or a character string, add a first column of row namesto the huxtable. The string gives the name for the new column (or"rownames" forTRUE).

autoformat

IfTRUE, automatically format columns by type. See below.

groups_to_headers

Logical. Convert groups to header rows?

Details

is_hux[table] tests if an object is a huxtable.

Fortable objects,add_colnames andadd_rownames areTRUE by default. Formatrix objects, they areFALSE. Other classes useoptions("huxtable.add_colnames"), which isTRUE by default;add_rownamesisFALSE.

Fordplyr::grouped_df() objects, groups will be converted to header rowsifgroups_to_headers isTRUE.

Value

An object of class "huxtable".

Examples

dfr <- data.frame(  a = 1:5,  b = letters[1:5],  stringsAsFactors = FALSE)as_huxtable(dfr)mx <- matrix(letters[1:12], 4, 3)as_huxtable(mx, add_colnames = FALSE)library(stats)tbl <- table(  Wool    = warpbreaks$wool,  Tension = warpbreaks$tension)as_huxtable(tbl) # adds row and column names by default# adding rownames:as_hux(mtcars[1:3, ],  add_colnames = TRUE,  add_rownames = "Car")if (requireNamespace("dplyr")) {  iris_grp <- dplyr::group_by(iris[c(1:4, 51:54, 101:104), ], Species)  as_hux(iris_grp, groups_to_headers = TRUE)}

Set cell background color

Description

Colors can be in any format understood by R:

Usage

background_color(ht)background_color(ht) <- valueset_background_color(ht, row, col, value)map_background_color(ht, row, col, fn)

Arguments

ht

A huxtable.

value

A character vector or matrix. Set toNA to reset to the default, which isNA_character_.

row

A row specifier. Seerowspecs for details.

col

An optional column specifier.

fn

A mapping function. Seemapping-functions for details.

Details

Transparent colors are not guaranteed to work at present.

See Also

Other formatting functions:bold(),font(),font_size(),na_string(),number_format(),text_color()

Examples

background_color(jams) <- grey(0.7)background_color(jams)set_background_color(jams, "yellow")set_background_color(jams, 2:3, 1, "yellow")map_background_color(jams, by_rows("yellow", grey(0.7)))

Make cell text bold or italic

Description

Make cell text bold or italic

Usage

bold(ht)bold(ht) <- valueset_bold(ht, row, col, value = TRUE)map_bold(ht, row, col, fn)italic(ht)italic(ht) <- valueset_italic(ht, row, col, value = TRUE)map_italic(ht, row, col, fn)

Arguments

ht

A huxtable.

value

A logical vector or matrix. Set toNA to reset to the default, which isFALSE.

row

A row specifier. Seerowspecs for details.

col

An optional column specifier.

fn

A mapping function. Seemapping-functions for details.

See Also

Other formatting functions:background_color(),font(),font_size(),na_string(),number_format(),text_color()

Examples

bold(jams) <- TRUEbold(jams)set_bold(jams, FALSE)set_bold(  jams,  2:3, 1, FALSE)map_bold(  jams,  by_rows(FALSE, TRUE))

Create a border object

Description

brdr() objects can be passed intoset_top_border() and friends.They set multiple border properties simultaneously.

Usage

brdr(thickness = 0.4, style = "solid", color = NA_character_)

Arguments

thickness

Thickness of the border in points.

style

"solid" (the default), "double", "dashed" or "dotted".

color

String representing a valid color (either a color name ora hexadecimalstring like "#00FF00").

Value

An object of class "brdr".

Examples

set_bottom_border(jams, brdr(1, "solid", "red"))

Get thickness of abrdr() object

Description

Get thickness of abrdr() object

Usage

brdr_thickness(x)

Arguments

x

Abrdr() object.

Value

A number or numeric matrix.

Examples

brdr_thickness(left_border(jams))brdr_thickness(brdr(1, "solid", "red"))

Map cell contents to properties usingcase_when

Description

This function usesdplyr::case_when() to set cell properties.

Usage

by_cases(..., ignore_na = TRUE)

Arguments

...

A list of two-sided formulas interpreted bycase_when.

ignore_na

IfTRUE,NA values in the result will be left unchangedfrom their previous values. Otherwise,NAnormally resets to the default.

Details

Within the formulas, the variable. will refer to the content ofht[rows, cols], after conversion to a vector.

case_when returnsNA when no formula LHS is matched. To avoid this, set adefault in the last formula:TRUE ~ default.

case_when can't deal withbrdr() objects, so you cannot usethese inby_cases().

Value

A function for use in⁠map_***⁠ functions.

See Also

mapping-functions

Other mapping functions:by_colorspace(),by_function(),by_quantiles(),by_ranges(),by_regex(),by_rows(),by_values()

Examples

if (!requireNamespace("dplyr")) {  stop("Please install the 'dplyr' package to run this example")}ht <- hux(runif(5), letters[1:5])map_background_color(ht, by_cases(  . == "a" ~ "red",  . %in% letters ~ "green",  . < 0.5 ~ "pink"))

Map numeric cell contents smoothly to colors

Description

by_colorspace() can be used to set background, border ortext colors, visually differentiating high or low values.

Usage

by_colorspace(  ...,  range = NULL,  na_color = NA,  ignore_na = TRUE,  colwise = FALSE)

Arguments

...

Colors

range

Numeric endpoints. IfNULL, these are determined from the data.

na_color

Color to return forNA values. Can beNA itself.

ignore_na

IfTRUE,NA values in the result will be left unchangedfrom their previous values. Otherwise,NAnormally resets to the default.

colwise

Logical. Calculate breaks separately within each column?

Details

by_colorspace requires the "scales" package.

Value

A function for use in⁠map_***⁠ functions.

See Also

mapping-functions

Other mapping functions:by_cases(),by_function(),by_quantiles(),by_ranges(),by_regex(),by_rows(),by_values()

Examples

if (!requireNamespace("scales")) {  stop("Please install the \"scales\" package to run this example")}ht <- as_hux(matrix(rnorm(25), 5, 5))map_background_color(  ht,  by_colorspace("red", "yellow", "blue"))map_background_color(  ht,  by_colorspace("red", "yellow", "blue",    colwise = TRUE  ))

Map cell contents to cell properties using a function or scale

Description

This creates a simple wrapper around a function for use inmap_xxx.Useful functions include scales and palettes from thescales package.

Usage

by_function(inner_fn, ignore_na = TRUE)

Arguments

inner_fn

A one-argument function which maps cell values to property values.

ignore_na

IfTRUE,NA values in the result will be left unchangedfrom their previous values. Otherwise,NAnormally resets to the default.

Details

The argument ofinner_fn will beas.matrix(ht[row, col]). Be aware how matrix conversionaffects themode of cell data.

Value

A function for use in⁠map_***⁠ functions.

See Also

mapping-functions

Other mapping functions:by_cases(),by_colorspace(),by_quantiles(),by_ranges(),by_regex(),by_rows(),by_values()

Examples

ht <- as_hux(matrix(runif(20), 5, 4))map_background_color(  ht,  by_function(grey))if (requireNamespace("scales")) {  map_text_color(ht, by_function(    scales::seq_gradient_pal()  ))}

Map numeric quantiles to cell properties

Description

These functions split cell values by quantiles. Non-numeric cells are ignored.

Usage

by_quantiles(  quantiles,  values,  right = FALSE,  extend = TRUE,  ignore_na = TRUE,  colwise = FALSE)by_equal_groups(n, values, ignore_na = TRUE, colwise = FALSE)

Arguments

quantiles

Vector of quantiles.

values

Vector of values.length(values) should be one greater thanlength(quantiles),or one less ifextend = FALSE.

right

IfTRUE, intervals are closed on the right, i.e. if values are exactly equal to abreak, they go in the lower group. Otherwise, intervals are closed on the left, so equalvalues go in the higher group.FALSE by default.

extend

Extendbreaks toc(-Inf, breaks, Inf), i.e. include numbers below and above theoutermost breaks.TRUE by default.

ignore_na

IfTRUE,NA values in the result will be left unchangedfrom their previous values. Otherwise,NAnormally resets to the default.

colwise

Logical. Calculate breaks separately within each column?

n

Number of equal-sized groups.length(values) should equaln.

Details

by_equal_groups(n, values) splits the data inton equal-sized groups (i.e. it is a shortcutforby_quantiles(seq(1/n, 1 - 1/n, 1/n), values)).

Value

A function for use in⁠map_***⁠ functions.

See Also

mapping-functions

Other mapping functions:by_cases(),by_colorspace(),by_function(),by_ranges(),by_regex(),by_rows(),by_values()

Examples

ht <- hux(rnorm(5), rnorm(5))map_background_color(  ht,  by_quantiles(    c(0.2, 0.8),    c("red", "yellow", "green")  ))map_background_color(  ht,  by_quantiles(    c(0.2, 0.8),    c("red", "yellow", "green"),    colwise = TRUE  ))map_background_color(  ht,  by_equal_groups(    3,    c("red", "yellow", "green")  ))

Map numeric ranges to cell properties

Description

by_ranges() sets property values for cells falling within different numeric ranges.

Usage

by_ranges(breaks, values, right = FALSE, extend = TRUE, ignore_na = TRUE)

Arguments

breaks

A vector of numbers in increasing order.

values

A vector of property values.length(values) should be one greater thanlength(breaks) ifextend = TRUE, or one less ifextend = FALSE.

right

IfTRUE, intervals are closed on the right, i.e. if values are exactly equal to abreak, they go in the lower group. Otherwise, intervals are closed on the left, so equalvalues go in the higher group.FALSE by default.

extend

Extendbreaks toc(-Inf, breaks, Inf), i.e. include numbers below and above theoutermost breaks.TRUE by default.

ignore_na

IfTRUE,NA values in the result will be left unchangedfrom their previous values. Otherwise,NAnormally resets to the default.

Details

Non-numeric cells returnNA. The effects of this depend onignore_na.

Value

A function for use in⁠map_***⁠ functions.

See Also

mapping-functions

Other mapping functions:by_cases(),by_colorspace(),by_function(),by_quantiles(),by_regex(),by_rows(),by_values()

Examples

ht <- huxtable(c(1, 3, 5))map_background_color(  ht,  by_ranges(    c(2, 4),    c("red", "yellow", "blue")  ))map_background_color(  ht,  by_ranges(    c(2, 4),    "pink",    extend = FALSE  ))map_background_color(  ht,  by_ranges(    c(1, 5),    c("red", "yellow", "green"),    right = TRUE  ))map_background_color(  ht,  by_ranges(    c(1, 5),    c("red", "yellow", "green"),    right = FALSE  ))

Map cells matching a string or regex to cell properties

Description

by_regex() sets properties on cells which match aregular expression.

Usage

by_regex(..., .grepl_args = list(), ignore_na = TRUE)

Arguments

...

A list of name-value pairs. The names are regular expressions. If there is a singleunnamed argument, this is the default value for unmatched cells. More than one unnamed argumentis an error.

.grepl_args

A list of arguments to pass togrepl(). Useful optionsincludefixed,perl andignore.case.

ignore_na

IfTRUE,NA values in the result will be left unchangedfrom their previous values. Otherwise,NAnormally resets to the default.

Value

A function for use in⁠map_***⁠ functions.

See Also

mapping-functions

Other mapping functions:by_cases(),by_colorspace(),by_function(),by_quantiles(),by_ranges(),by_rows(),by_values()

Examples

ht <- hux(c("The cat sat", "on the", "mat"))map_bold(ht, by_regex("at" = TRUE))map_bold(ht, by_regex("a.*a" = TRUE))map_bold(ht, by_regex(  "the" = TRUE,  .grepl_args = list(    ignore.case = TRUE  )))

Set cell properties by row or column

Description

by_rows andby_cols set properties in horizontal or vertical "stripes".

Usage

by_rows(..., from = 1, ignore_na = TRUE)by_cols(..., from = 1, ignore_na = TRUE)

Arguments

...

One or more cell property values.

from

Numeric. Row or column to start at.

ignore_na

IfTRUE,NA values in the result will be left unchangedfrom their previous values. Otherwise,NAnormally resets to the default.

Value

A function for use in⁠map_***⁠ functions.

See Also

mapping-functions

Other mapping functions:by_cases(),by_colorspace(),by_function(),by_quantiles(),by_ranges(),by_regex(),by_values()

Examples

ht <- as_hux(matrix(rnorm(25), 5, 5))map_background_color(  ht,  by_rows("green", "grey"))map_background_color(  ht,  by_cols("green", "grey"))

Map specific cell values to cell properties

Description

Useby_values() to set properties for cells with specific,pre-determined contents.

Usage

by_values(..., ignore_na = TRUE)

Arguments

...

Name-value pairs likename = value. Cells where contents are equal toname will have the property set tovalue. If there is a single unnamed argument,this is the default value for unmatched cells. More than one unnamed argument is an error.

ignore_na

IfTRUE,NA values in the result will be left unchangedfrom their previous values. Otherwise,NAnormally resets to the default.

Value

A function for use in⁠map_***⁠ functions.

See Also

mapping-functions

Other mapping functions:by_cases(),by_colorspace(),by_function(),by_quantiles(),by_ranges(),by_regex(),by_rows()

Examples

ht <- hux(letters[1:3])map_background_color(  ht,  by_values(a = "red", c = "yellow"))map_background_color(  ht,  by_values(a = "red", c = "yellow", "green"))

Set the table caption

Description

By default, captions are displayed above the table. You can change thiswithcaption_pos().

Usage

caption(ht)caption(ht) <- valueset_caption(ht, value)

Arguments

ht

A huxtable.

value

A string. Set toNA to reset to the default, which isNA_character_.

Details

Captions are not escaped. See the example for a workaround.

Value

property() returns the property value(s).set_property() andmap_property() return the modified huxtable.

See Also

Other caption properties:caption_pos(),caption_width()

Examples

set_caption(jams, "Pots of jam for sale")# escape caption characters:caption(jams) <- sanitize(  "Make $$$ with jam",  type = "latex")

Position the table's caption

Description

Ifcaption_pos is "top" or "bottom", then the horizontal position ("left","center" or "right") will be determined by the huxtable"sposition().

Usage

caption_pos(ht)caption_pos(ht) <- valueset_caption_pos(ht, value)

Arguments

ht

A huxtable.

value

String: "top", "bottom", "topleft", "topcenter", "topright", "bottomleft", "bottomcenter" or "bottomright". Set toNA to reset to the default, which is"top".

Value

property() returns the property value(s).set_property() andmap_property() return the modified huxtable.

See Also

Other caption properties:caption(),caption_width()

Examples

caption(jams) <- "Jam for sale"jamsset_caption_pos(jams, "bottom")

Set the width of the table caption

Description

A numeric widths is interpreted as a proportion of text width in LaTeX, or ofwidth of the containing element in HTML. A character width must be a validLaTeX or CSS dimension. The default,NA, makes the caption the same widthas the table.

Usage

caption_width(ht)caption_width(ht) <- valueset_caption_width(ht, value)

Arguments

ht

A huxtable.

value

Number or string. Set toNA to reset to the default, which isNA_real_.

Value

property() returns the property value(s).set_property() andmap_property() return the modified huxtable.

See Also

Other caption properties:caption(),caption_pos()

Examples

set_caption_width(jams, 0.5)

Combine rows or columns

Description

These methods are called when one argument tocbind/rbind is ahuxtable. As well as combining cell contents, they copy table, row,column and/or cell properties into the returned result.

Usage

## S3 method for class 'huxtable'cbind(..., deparse.level = 1, copy_cell_props = TRUE)## S3 method for class 'huxtable'rbind(..., deparse.level = 1, copy_cell_props = TRUE)

Arguments

...

Vectors, matrices, or huxtables.

deparse.level

Unused.

copy_cell_props

Cell properties to copy from neighbours (see below).

Details

Table properties will be taken from the first argument which is a huxtable. So willrow properties (for cbind) and column properties (for rbind).

If some of the inputs are not huxtables, andcopy_cell_props isTRUE,then cell properties will be copied to non-huxtables. Objects on the leftor above get priority over those on the right or below.

Ifcopy_cell_props isFALSE, cells from non-huxtable objects will get the default properties.

You cannot bind huxtables with data frames, since the R method dispatch will alwayscall the data frame method instead of the huxtable-specific code. For a solution, seeadd_columns().

Value

A huxtable.

Examples

sugar <- c("Sugar", "40%", "35%", "50%")jams <- set_bold(jams, 1, everywhere)cbind(jams, sugar)cbind(jams, sugar,  copy_cell_props = FALSE)jams <- set_text_color(  jams,  everywhere, 1, "red")rbind(jams, c("Damson", 2.30))rbind(jams, c("Damson", 2.30),  copy_cell_props = FALSE)

Set the width of table columns

Description

Numeric column widths are treated as proportions of the table width.Character widths must be valid CSS or LaTeX dimensions.

Usage

col_width(ht)col_width(ht) <- valueset_col_width(ht, col, value)

Arguments

ht

A huxtable.

value

Numeric or character vector. Set toNA to reset to the default,which is NA.

col

A column specifier. Seerowspecs for details.

Details

In LaTeX, if you specify a column width, but setwrap toFALSE and havecells which overrun, then you may have problems with table position and withbackground colours in other cells. The workaround is to adjust the width, sothat your cells no longer overrun.

Value

col_width() returns thecol_width property.set_col_width() returns the modified huxtable.

See Also

Other table measurements:height(),row_height(),width()

Examples

col_width(jams) <- c(.2, .8)col_width(jams)jams$Notes <- c(  "Notes",  "This year's finest", "", "")jamsset_col_width(jams, c(.4, .5, .1))

Convert a column to header rows

Description

Convert a column to header rows

Usage

column_to_header(  ht,  col,  ...,  glue = "{value}",  start_col = 1,  ignore_headers = TRUE,  set_headers = TRUE)

Arguments

ht

A huxtable.

col

A column specifier for a single column.

...

Properties to set on new rows

glue

Glue string."{value}" will be replaced by the column value.

start_col

Integer. New header text will start at this column.

ignore_headers

Logical. Ignore existing headers?

set_headers

Logical. Set new rows as headers?

Examples

column_to_header(jams, "Type")column_to_header(jams, "Type", text_color = "red")column_to_header(jams, "Price",  number_format = 2,  italic = TRUE,  glue = "Price: {value}")iris_hux <- as_hux(iris[c(1:4, 51:54, 101:104), ])column_to_header(iris_hux, "Species",  markdown = TRUE,  glue = "Species: **{value}**")

Description of color format

Description

Colors can be in any format understood by R:


Escape or unescape text in cells

Description

Settingescape_contents toFALSE allows you to include raw HTML orTeX code in your cells.

Usage

escape_contents(ht)escape_contents(ht) <- valueset_escape_contents(ht, row, col, value)map_escape_contents(ht, row, col, fn)

Arguments

ht

A huxtable.

value

A logical vector or matrix. Set toNA to reset to the default, which isTRUE.

row

A row specifier. Seerowspecs for details.

col

An optional column specifier.

fn

A mapping function. Seemapping-functions for details.

Details

Ifmarkdown() isTRUE for a cell, theescape_contents propertywill be ignored.

See Also

sanitize() for escaping text manually.

Examples

ht <- huxtable(  Text   = "x squared",  Maths  = "$x^2$")ht <- set_escape_contents(ht, FALSE)## Not run: quick_pdf(ht)## End(Not run)

Return the last n rows or columns

Description

This is a convenience function to use in row and column specifications. In that context, itreturns the last n row or column numbers of the huxtable.

Usage

final(n = 1)

Arguments

n

Number of rows to return.

Details

Technically,final returns a two-argument function - seerowspecs for more details.

Examples

set_bold(jams, final(2), final(1), TRUE)

Description forfmt_ functions

Description

fmt_ functions are designed to work withnumber_format().

Value

An object you can pass intonumber_format().


Format numbers as percent

Description

fmt_ functions are designed to work withnumber_format().

Usage

fmt_percent(digits = 1, format = "f", ...)

Arguments

digits

How many digits to print.

format,...

Passed intoformatC().

Value

An object you can pass intonumber_format().

See Also

Other format functions:fmt_pretty()

Examples

jams$Sugar <- c(  "Sugar content",  0.4, 0.35, 0.45)set_number_format(  jams, -1, "Sugar",  fmt_percent(1))

UseprettyNum() to format numbers

Description

UseprettyNum() to format numbers

Usage

fmt_pretty(big.mark = ",", ..., scientific = FALSE)

Arguments

big.mark,scientific,...

Passed toprettyNum().

Value

An object you can pass intonumber_format().

See Also

Other format functions:fmt_percent()

Examples

jams$Sales <- c(  "Sales", 35000,  55500, 20000)set_number_format(  jams, -1, "Sales",  fmt_pretty())

Set the font for cell text

Description

Set the font for cell text

Usage

font(ht)font(ht) <- valueset_font(ht, row, col, value)map_font(ht, row, col, fn)

Arguments

ht

A huxtable.

value

A character vector or matrix. Set toNA to reset to the default, which isNA_character_.

row

A row specifier. Seerowspecs for details.

col

An optional column specifier.

fn

A mapping function. Seemapping-functions for details.

Details

To find out what fonts are on your system,systemfonts::match_font()is useful.

For HTML, you can use comma-separated lists of font names like"Times New Roman, Times, Serif". This is not portable, though.

LaTeX and HTML use different font names. To use the same fontnames across document formats, seeoptions("huxtable.latex_use_fontspec")inhuxtable-options.

See Also

Other formatting functions:background_color(),bold(),font_size(),na_string(),number_format(),text_color()

Examples

font(jams) <- "times"font(jams)set_font(jams, "arial")set_font(jams, 2:3, 1, "arial")map_font(jams, by_rows("arial", "times"))

Make text larger or smaller

Description

Font size is in points.

Usage

font_size(ht)font_size(ht) <- valueset_font_size(ht, row, col, value)map_font_size(ht, row, col, fn)

Arguments

ht

A huxtable.

value

A numeric vector. Set toNA to reset to the default, which isNA_real_.

row

A row specifier. Seerowspecs for details.

col

An optional column specifier.

fn

A mapping function. Seemapping-functions for details.

See Also

Other formatting functions:background_color(),bold(),font(),na_string(),number_format(),text_color()

Examples

font_size(jams) <- 14font_size(jams)jams2 <- set_font_size(  jams,  12)font_size(jams2)jams3 <- set_font_size(  jams,  2:3, 1, 12)font_size(jams3)jams4 <- map_font_size(  jams,  by_rows(    12,    14  ))font_size(jams4)

Guess knitr output format

Description

Convenience function which tries to guess the ultimate output from knitr and rmarkdown.

Usage

guess_knitr_output_format()

Value

"html", "latex", "typst", or something else. If we are not in a knitr document,returns an empty string.

Examples

## Not run: # in a knitr documentguess_knitr_output_format()## End(Not run)

Mark rows or columns as headers

Description

Arbitrary rows and columns can be headers: they do not have to be at the topor left of the table.

Usage

header_cols(ht)header_cols(ht) <- valueset_header_cols(ht, col, value)header_rows(ht)header_rows(ht) <- valueset_header_rows(ht, row, value)

Arguments

ht

A huxtable.

value

Logical vector. Set toNA to reset to the default,which is FALSE.

col

A column specifier. Seerowspecs for details.

row

A row specifier. Seerowspecs for details.

Details

By default header rows and columns are not shown differently from other rows, butyou can change this withstyle_headers().Various themes may set properties on headers. Lastly, headers are treateddifferently whenrestacking.

Examples

jams <- set_header_rows(jams, 1, TRUE)jams <- set_header_cols(jams, 1, TRUE)style_headers(jams,  bold       = TRUE,  text_color = "purple")

Set the table height

Description

height() sets the height of the entire table, whilerow_height() sets theheight of individual rows. A numeric height is treated as a proportion ofthe containing block (HTML) or⁠\textheight⁠ (LaTeX). A character heightmust be a valid CSS or LaTeX dimension.

Usage

height(ht)height(ht) <- valueset_height(ht, value)

Arguments

ht

A huxtable.

value

A number or string. Set toNA to reset to the default, which isNA_real_.

Value

property() returns the property value(s).set_property() andmap_property() return the modified huxtable.

See Also

Other table measurements:col_width(),row_height(),width()

Examples

set_height(jams, 0.4)

Description

Returns a randomized huxtable logo, inspired by Mondrian.

Usage

hux_logo(compact = FALSE, latex = NULL)

Arguments

compact

Logical. Create a compact 1-row huxtable (default is 2 rows)?

latex

Logical. Output for LaTeX?

Value

A huxtable.

Examples

# Default logoprint_screen(hux_logo())# Compact single-row versionprint_screen(hux_logo(compact = TRUE))

Shared documentation for huxtable property functions:

Description

Shared documentation for huxtable property functions:

Arguments

ht

A huxtable.

row

A row specifier. Seerowspecs for details.

col

An optional column specifier.

fn

A mapping function. Seemapping-functions for details.

Value

property() returns the property value(s).set_property() andmap_property() return the modified huxtable.


Create a huxtable to display model output

Description

Create a huxtable to display model output

Usage

huxreg(  ...,  error_format = "({std.error})",  error_pos = c("below", "same", "right"),  number_format = "%.3f",  align = ".",  ci_level = NULL,  tidy_args = NULL,  glance_args = NULL,  stars = c(`***` = 0.001, `**` = 0.01, `*` = 0.05),  bold_signif = NULL,  borders = 0.4,  outer_borders = 0.8,  note = if (is.null(stars)) NULL else "{stars}.",  statistics = c(N = "nobs", R2 = "r.squared", "logLik", "AIC"),  coefs = NULL,  omit_coefs = NULL)

Arguments

...

Models, or a single list of models. Names will be used as columnheadings.

error_format

How to display uncertainty in estimates. See below.

error_pos

Display uncertainty "below", to the "right" of, or in the"same" cell as estimates.

number_format

Format for numbering. Seenumber_format() for details.

align

Alignment for table cells. Set to a single character to align onthis character.

ci_level

Confidence level for intervals. Set toNULL to notcalculate confidence intervals.

tidy_args

List of arguments to pass togenerics::tidy().A list without names will be treated as a list of argument lists, onefor each model.

glance_args

List of arguments to pass togenerics::glance(). Alist without names will be treated as a list of argument lists, one foreach model.

stars

Levels for p value stars. Names ofstars are symbols to use.Set toNULL to not show stars.

bold_signif

Where p values are below this number, cells will bedisplayed in bold. UseNULL to turn off this behaviour.

borders

Thickness of inner horizontal borders. Set to 0 for no borders.

outer_borders

Thickness of outer (top and bottom) horizontal borders.Set to 0 for no borders.

note

Footnote for bottom cell, which spans all columns.{stars}will be replaced by a note about significance stars. Set toNULL for nofootnote.

statistics

A vector of summary statistics to display. Set toNULL toshow all available statistics. To change display names, name thestatistics vector:c("Displayed title" = "statistic_name", ...)

coefs

A vector of coefficients to display. Overrulesomit_coefs. Tochange display names, name thecoef vector:c("Displayed title" = "coefficient_name", ...)

omit_coefs

Omit these coefficients.

Details

Models must have agenerics::tidy() method defined, which should return "term", "estimate","std.error", "statistic" and "p.value". The"broom" package provides methods for many modelobjects. If thetidy method does not have aconf.int option,huxreg will calculate confidence intervals itself, using a normal approximation.

If... has names or contains a single named list, the names will be used for column headings.Otherwise column headings will be automatically created.

If thecoef and/orstatistics vectors have names, these will be used for row headings. Ifdifferent values ofcoef have the same name, the corresponding rows will be merged in theoutput.

statistics should be column names fromgenerics::glance(). You can also use"nobs" for thenumber of observations. Ifstatistics isNULL then all columns fromglance will be used. Touse no columns, setstatistics = character(0).

error_format is a string to be interpreted byglue::glue(). Terms in parentheses will bereplaced by computed values. You can use any columns returnedbytidy: typical columns includestatistic,p.value,std.error, as well asconf.lowandconf.high if you have setci_level. For example, to show confidence intervals, youcould writeerror_format = "{conf.low} to {conf.high}".

Value

A huxtable object.

Fixing p values manually

If you wish to use e.g. robust standard errors, you can pass results from e.g.lmtest::coeftest() intohuxreg, since these objects havetidy methods.Alternatively, to manually insert your own statistics, seetidy_override().

Examples

if (!requireNamespace("broom")) {  stop("Please install 'broom' to run this example.")}lm1 <- lm(mpg ~ cyl, mtcars)lm2 <- lm(mpg ~ cyl + hp, mtcars)glm1 <- glm(I(mpg > 20) ~ cyl, mtcars,  family = binomial)huxreg(lm1, lm2, glm1)if (requireNamespace("sandwich") &&  requireNamespace("lmtest")) {  lm_robust <- lmtest::coeftest(lm1,    vcov = sandwich::vcovHC  )  # coeftest() has no "glance" method:  huxreg(lm_robust,    statistics = character(0)  )}

Create a huxtable

Description

huxtable, orhux, creates a huxtable object.

Usage

huxtable(  ...,  add_colnames = getOption("huxtable.add_colnames", TRUE),  add_rownames = FALSE,  autoformat = getOption("huxtable.autoformat", TRUE))hux(  ...,  add_colnames = getOption("huxtable.add_colnames", TRUE),  add_rownames = FALSE,  autoformat = getOption("huxtable.autoformat", TRUE))tribble_hux(  ...,  add_colnames = getOption("huxtable.add_colnames", TRUE),  autoformat = getOption("huxtable.autoformat", TRUE))

Arguments

...

Forhuxtable, named list of values as indata.frame().Fortribble_hux, data values as intibble::tribble().

add_colnames

IfTRUE, add a first row of column names to the huxtable.

add_rownames

IfTRUE or a character string, add a first column of row namesto the huxtable. The string gives the name for the new column (or"rownames" forTRUE).

autoformat

IfTRUE, automatically format columns by type. See below.

Details

If you useadd_colnames oradd_rownames, be aware that these will shift your rows and columnsalong by one: your old row/column 1 will now be row/column 2, etc.

add_colnames defaults toTRUE. You can set the default globally bysettingoptions("huxtable.add_colnames") toTRUE orFALSE.

tribble_hux is a simple wrapper aroundtibble::tribble() which lets youcreate data in a readable format. It requires the "tibble" package tobe installed.

Value

An object of classhuxtable.

Automatic formatting

Ifautoformat isTRUE, then columns will havenumber_format() andalign() propertiesset automatically, as follows:

You can change these defaults by editingoptions("huxtable.autoformat_number_format") andoptions("huxtable.autoformat_align"). Seehuxtable-package for more details.

Automatic alignment also applies to column headers ifadd_colnames isTRUE; headers ofcolumns aligned on a decimal point will be right-aligned. Automatic number formatting does notapply to column headers.

See Also

huxtable-options

Examples

ht <- huxtable(  column1 = 1:5,  column2 = letters[1:5])httribble_hux(  ~Name, ~Salary,  "John Smith", 50000,  "Jane Doe", 50000,  "David Hugh-Jones", 50000,  add_colnames = TRUE)

Frequently Asked Questions, including how to get help

Description

A FAQ of common issues.

Details

If you really need cross-referencing for both PDF and other outputformats, either downgrade to quarto 1.3, use a different package,or write code to emit appropriate references.

Author(s)

Maintainer: David Hugh-Jonesdavidhughjones@gmail.com

See Also

Useful links:


Changes to the huxtable package

Description

This help page simply gives the contents of NEWS.md.

huxtable 5.8.0

Other changes

huxtable 5.7.0

Breaking changes

Other changes

huxtable 5.6.0

Breaking changes

Other changes

huxtable 5.5.7

huxtable 5.5.6

huxtable 5.5.5

huxtable 5.5.3

huxtable 5.5.2

huxtable 5.5.1

huxtable 5.5.0

huxtable 5.4.0

huxtable 5.3.0

huxtable 5.2.0

huxtable 5.1.1

huxtable 5.1.0

Other news:

huxtable 5.0.0

Huxtable 5.0.0 brings numerous changes. For a more user-friendlyintroduction, seehttps://hughjonesd.github.io/whats-new-in-huxtable-5.0.0.html.

Breaking changes

Other changes

Other news

huxtable 4.7.1

huxtable 4.7.0

huxtable 4.6.1

huxtable 4.6.0

huxtable 4.5.0

huxtable 4.4.0

huxtable 4.3.0

Deprecated

huxtable 4.2.1

Important

huxtable 4.2.0

huxtable 4.1.0

huxtable 4.0.1

huxtable 4.0.0

Breaking changes

Bugfixes

huxtable 3.0.0

Breaking changes

huxtable 2.0.2

huxtable 2.0.1

huxtable 2.0.0

Breaking changes

huxtable 1.2.0

huxtable 1.1.0

huxtable 1.0.0

Breaking changes

huxtable 0.3.1

huxtable 0.3.0

huxtable 0.2.2

huxtable 0.2.1

huxtable 0.2.0

Breaking changes

huxtable 0.1.0

Author(s)

Maintainer: David Hugh-Jonesdavidhughjones@gmail.com

See Also

Useful links:


Package options

Description

Huxtable has several options.

Details

Author(s)

Maintainer: David Hugh-Jonesdavidhughjones@gmail.com

See Also

Useful links:


Insert a row or column

Description

These convenience functions wrapcbind orrbind for huxtables, to inserta single row or column.

Usage

insert_column(  ht,  ...,  after = 0,  fill = NULL,  rowspan = 1,  copy_cell_props = TRUE)insert_row(  ht,  ...,  after = 0,  fill = NULL,  colspan = 1,  copy_cell_props = TRUE)

Arguments

ht

A huxtable.

...

Cell contents.

after

Insert the row/column after this position. 0 (the default) inserts as the first row/column.

fill

String. If... contains fewer elements than there are columns/rows tofill, the remaining cells will be filled with this.

rowspan,colspan

Scalar integer. Sets the rowspan or colspan of thefirst cell only.The defaultNULL throws an error if there are too few elements.

copy_cell_props

Copy cell properties from the previous row or column (if after > 0). Seecbind.huxtable().

Details

Ininsert_column only, you can use a column name forafter.

Even ifcolspan orrowspan are greater than 1, you must still providevalues for the hidden cells. Usefill = "" for this.

Value

The modified huxtable

See Also

add_rows() andadd_columns(), which insert multiple rows/columns at once.

Examples

insert_row(jams,  c("Gooseberry", 2.15),  after = 1)insert_column(jams,  c("Sugar", "50%", "60%", "40%"),  after = "Price")insert_column(jams,  "Sugar",  after = "Price",  fill = "50%")# don't forget to use `fill`:insert_row(jams,  "Jams and prices",  fill = "",  colspan = 2)

Prices of 3 jams

Description

A huxtable of jams.

Usage

jams

Format

A huxtable with 4 rows and 2 columns ("Type" and "Price").


Print data frames in knitr using huxtable

Description

Print data frames in knitr using huxtable

Usage

knit_print.data.frame(x, options, ...)

Arguments

x

A huxtable.

options

Not used.

...

Not used.

Details

huxtable defines aknit_print method fordata.frames. This converts the data frameto a huxtable, withadd_colnames = TRUE, themes it usingtheme_plain() and prints it.It also tries to set a few intelligent defaults, e.g. wrapping long columns and settingan appropriate width.To turn this behaviour off, setoptions(huxtable.knit_print_df = FALSE). To change the theme, setoptions("huxtable.knit_print_df_theme") to a one-argument function which should return the huxtable.

See Also

huxtable-options

Other knit_print:knit_print.huxtable()

Examples

## Not run: # in your knitr documentmytheme <- function(ht) {  ht <- set_all_borders(ht, 0.4)  ht <- set_all_border_colors(    ht,    "darkgreen"  )  ht <- set_background_color(    ht,    evens, odds, "salmon"  )  ht}options(  huxtable.knit_print_df_theme = mytheme)# groovy!data.frame(  a = 1:5,  b = 1:5)## End(Not run)

Print a huxtable within knitr

Description

Print a huxtable within knitr

Usage

knit_print.huxtable(x, options, ...)

Arguments

x

A huxtable.

options

Not used.

...

Not used.

Details

knitr callsknitr::knit_print() on objects when they are printed in a knitr (or RMarkdown) document.The method forhuxtable objects guesses the appropriate output format(including Typst documents when using thetypst package) andprints itself out appropriately. You can override the output format by settingoptions("huxtable.knitr_output_format").

See Also

huxtable-options

Other knit_print:knit_print.data.frame()


Set a table label for external referencing

Description

The label is used as the table's label in LaTeX, and as the "id" propertyof the table element in HTML.

Usage

label(ht)label(ht) <- valueset_label(ht, value)

Arguments

ht

A huxtable.

value

A string. Set toNA to reset to the default, which isNA_character_.

Details

LaTeX table labels typically start with"tab:".

Within knitr, huxtable labels will default to the same as the knitr chunk label.To turn off this behaviour, setoptions(huxtable.autolabel = FALSE).

If you usebookdown, and set a label on yourtable, the tablecaption() will automatically be prefixed with⁠(#label)⁠.You can then refer to the table using⁠@ref(label)⁠.label needs to startwith"tab:"; if it doesn't, the"tab:" prefix will be addedautomatically. To turn off this behaviour, setoptions(huxtable.bookdown = FALSE).

Value

property() returns the property value(s).set_property() andmap_property() return the modified huxtable.

See Also

huxtable-options

Examples

set_label(jams, "tab:mytable")

Set the position of the table float in LaTeX

Description

Possible values include:

Usage

latex_float(ht)latex_float(ht) <- valueset_latex_float(ht, value)

Arguments

ht

A huxtable.

value

A string. Set toNA to reset to the default, which is"ht".

Details

See LaTeX documentation for more details.

Value

property() returns the property value(s).set_property() andmap_property() return the modified huxtable.

Examples

set_latex_float(jams, "b")

Set borders

Description

These functions set borders between cells.

Usage

left_border(ht)right_border(ht)top_border(ht)bottom_border(ht)left_border(ht) <- valueright_border(ht) <- valuetop_border(ht) <- valuebottom_border(ht) <- valueset_left_border(ht, row, col, value = 0.4)set_right_border(ht, row, col, value = 0.4)set_top_border(ht, row, col, value = 0.4)set_bottom_border(ht, row, col, value = 0.4)map_left_border(ht, row, col, fn)map_right_border(ht, row, col, fn)map_top_border(ht, row, col, fn)map_bottom_border(ht, row, col, fn)

Arguments

ht

A huxtable.

value

A numeric thickness or abrdr() object. Set toNA to reset to the default, which is0.

row

A row specifier. Seerowspecs for details.

col

An optional column specifier.

fn

A mapping function. Seemapping-functions for details.

Details

Borders are always "collapsed":right_border(ht)[, 1] is the same asleft_border(ht)[, 2], and setting one sets the other.

Settingleft_border(ht) <- number sets the border thickness. You can setmultiple properties at once by usingbrdr().

Currently in LaTeX, all non-zero border widths on a given line must be thesame.

Limitations

See Also

set-multiple

Other border properties:left_border_color(),left_border_style()

Examples

bottom_border(jams)[1, ] <- 0.4jamsbottom_border(jams)[1, ] <- brdr(0.4, "solid", "blue")jamsset_bottom_border(jams, brdr(0.4, "solid", "green"))

Set border colors

Description

These functions set border colors.

Usage

left_border_color(ht)right_border_color(ht)top_border_color(ht)bottom_border_color(ht)left_border_color(ht) <- valueright_border_color(ht) <- valuetop_border_color(ht) <- valuebottom_border_color(ht) <- valueset_left_border_color(ht, row, col, value)set_right_border_color(ht, row, col, value)set_top_border_color(ht, row, col, value)set_bottom_border_color(ht, row, col, value)map_left_border_color(ht, row, col, fn)map_right_border_color(ht, row, col, fn)map_top_border_color(ht, row, col, fn)map_bottom_border_color(ht, row, col, fn)

Arguments

ht

A huxtable.

value

A valid R color, e.g."red","#FF0000". Set toNA to reset to the default, which isNA_character_.

row

A row specifier. Seerowspecs for details.

col

An optional column specifier.

fn

A mapping function. Seemapping-functions for details.

Details

Borders are always "collapsed":right_border_color(ht)[, 1] is the same asleft_border_color(ht)[, 2], and setting one sets the other.

Limitations

See Also

set-multiple,brdr()

Other border properties:left_border(),left_border_style()

Examples

jams <- set_all_borders(jams)bottom_border_color(jams)[1, ] <- "red"jamsset_bottom_border_color(jams, "blue")

Set border styles

Description

These functions set border styles.

Usage

left_border_style(ht)right_border_style(ht)top_border_style(ht)bottom_border_style(ht)left_border_style(ht) <- valueright_border_style(ht) <- valuetop_border_style(ht) <- valuebottom_border_style(ht) <- valueset_left_border_style(ht, row, col, value)set_right_border_style(ht, row, col, value)set_top_border_style(ht, row, col, value)set_bottom_border_style(ht, row, col, value)map_left_border_style(ht, row, col, fn)map_right_border_style(ht, row, col, fn)map_top_border_style(ht, row, col, fn)map_bottom_border_style(ht, row, col, fn)

Arguments

ht

A huxtable.

value

One of"solid","double","dashed" or"dotted". Set toNA to reset to the default, which is"solid".

row

A row specifier. Seerowspecs for details.

col

An optional column specifier.

fn

A mapping function. Seemapping-functions for details.

Details

Borders are always "collapsed":right_border_style(ht)[, 1] is the same asleft_border_style(ht)[, 2], and setting one sets the other.

Limitations

See Also

set-multiple,brdr()

Other border properties:left_border(),left_border_color()

Examples

jams <- set_all_borders(jams)bottom_border_style(jams)[1, ] <- "dotted"jamsset_bottom_border_style(jams, "double")

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.

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 amap_... function for each huxtable cell property. The syntax is:

  map_property(ht, row, col, fn)

whereproperty is the property name.

row andcol specify ranges of rows and columns. Seerowspecs fordetails. To set properties for the whole table, omitrow andcol:

  map_property(ht, fn)

Thefn argument is amapping function which maps cell contents toproperty values.

Caveat

Most functions convert the huxtable to a matrix usingas.matrix(). This canhave unexpected results if you mix character and numeric data. See theexample.

Technical details

fn takes four arguments: the entire original huxtableht, a numeric vector ofrows, a numeric vector ofcols, and thecurrent property values forht[rows, cols], as a matrix. It should returnthe new property values forht[rows, cols], as a matrix.

Examples

ht <- hux(Condition = 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 <- as_hux(matrix(rnorm(15), 5, 3))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 ohmap_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"))

Mapping parameters

Description

Mapping parameters

Arguments

values

A vector of property values.length(values) should be one greater thanlength(breaks) ifextend = TRUE, or one less ifextend = FALSE.

right

IfTRUE, intervals are closed on the right, i.e. if values are exactly equal to abreak, they go in the lower group. Otherwise, intervals are closed on the left, so equalvalues go in the higher group.FALSE by default.

extend

Extendbreaks toc(-Inf, breaks, Inf), i.e. include numbers below and above theoutermost breaks.TRUE by default.

ignore_na

IfTRUE,NA values in the result will be left unchangedfrom their previous values. Otherwise,NAnormally resets to the default.

colwise

Logical. Calculate breaks separately within each column?


Interpret cell content as markdown

Description

Cells where the markdown property isTRUE will be interpreted asmarkdown.

Usage

markdown(ht)markdown(ht) <- valueset_markdown(ht, row, col, value = TRUE)map_markdown(ht, row, col, fn)

Arguments

ht

A huxtable.

value

A logical vector or matrix. Set toNA to reset to the default, which isFALSE.

row

A row specifier. Seerowspecs for details.

col

An optional column specifier.

fn

A mapping function. Seemapping-functions for details.

Details

Markdown is currently implemented for HTML, Word, Powerpoint, RTF, LaTeX andon-screen display. Word requires theftExtra package.

Most formats usecommonmark, with the"strikethrough" extension enabled.

The following features are intended to work:

There are some quirks:

If you try to use markdown tables within a table cell, then seek psychiatrichelp.

Note

Markdown content in cells is completely separate from printing the wholetable as markdown usingprint_md(). When you setmarkdown toTRUE,huxtable itself interprets the cell contents as markdown, and spits out HTML,TeX or whatever.

See Also

set_markdown_contents(), a shortcut function.

Examples

jams[3, 2] <- "~2.10~ **Sale!** 1.50"set_markdown(jams, 3, 2)

Note about markdown vs.print_md()

Description

Note about markdown vs.print_md()

Note

Markdown content in cells is completely separate from printing the wholetable as markdown usingprint_md(). When you setmarkdown toTRUE,huxtable itself interprets the cell contents as markdown, and spits out HTML,TeX or whatever.


Merge cells across rows or down columns

Description

merge_across() creates multicolumn cells within each row.merge_down() creates multirow cells within each column.

Usage

merge_across(ht, row, col)merge_down(ht, row, col)

Arguments

ht

A huxtable.

row

A row specifier. Seerowspecs for details.

col

An optional column specifier.

Value

Theht object.

Cell content

In merged cell ranges, only the top left cell's content is displayed.In addition, when you merge cells (either by settingcolspan() orrowspan(), or usingmerge_cells() and friends) the content of the topleft cell is copied to other cells. This prevents unexpected changes tocontent if you reorder or subset rows and columns.

See Also

Other cell merging:merge_cells(),merge_repeated_rows()

Examples

ht <- as_hux(matrix(1:12, 4, 3, byrow = TRUE))ht <- set_all_borders(ht, 1)merge_across(ht, 2:4, 2:3)merge_down(ht, 2:4, 2:3)

Merge a range of cells

Description

merge_cells() merges a rectangle of cells into a single displayed cell,by settingcolspan() androwspan().

Usage

merge_cells(ht, row, col)

Arguments

ht

A huxtable.

row

A row specifier. Seerowspecs for details.

col

An optional column specifier.

Details

merge_cells(ht, c(min_row, max_row), c(min_col, max_col)) is equivalent to

  colspan(ht)[min_row, min_col] <- max_col - min_col + 1  rowspan(ht)[min_row, min_col] <- max_row - min_row + 1

Value

Theht object.

Cell content

In merged cell ranges, only the top left cell's content is displayed.In addition, when you merge cells (either by settingcolspan() orrowspan(), or usingmerge_cells() and friends) the content of the topleft cell is copied to other cells. This prevents unexpected changes tocontent if you reorder or subset rows and columns.

See Also

Other cell merging:merge_across(),merge_repeated_rows()

Examples

ht <- hux(a = 1:3, b = 1:3)ht <- set_all_borders(ht, 1)merge_cells(ht, 2:3, 1:2)

Merge repeated rows into multirow cells

Description

merge_repeated_rows() looks within each column forcontiguous groups of identical cells. These are mergedby settingrowspan(). Doing this helps remove redundantinformation from the table.

Usage

merge_repeated_rows(ht, row, col)

Arguments

ht

A huxtable.

row

A row specifier. Seerowspecs for details.

col

An optional column specifier.

Details

Ifrow contains gaps, results may be unexpected (and a warning is given).

Value

Theht object.

Cell content

In merged cell ranges, only the top left cell's content is displayed.In addition, when you merge cells (either by settingcolspan() orrowspan(), or usingmerge_cells() and friends) the content of the topleft cell is copied to other cells. This prevents unexpected changes tocontent if you reorder or subset rows and columns.

See Also

Other cell merging:merge_across(),merge_cells()

Examples

ht <- as_hux(jams[c(1, 2, 2, 3, 3, 4), ])ht <- add_columns(ht, c("Sugar", "30%", "40%", "30%", "40%", "30%"),  after = 1)htmerge_repeated_rows(ht)merge_repeated_rows(ht, everywhere, "Type")

Use dplyr verbs with huxtable objects

Description

Huxtable can be used with dplyr verbsdplyr::select(),dplyr::rename(),dplyr::relocate(),dplyr::slice(),dplyr::arrange(),dplyr::mutate()anddplyr::transmute(). These will return huxtables. Other verbs likedplyr::summarise() will simply return data frames as normal;dplyr::pull() will return a vector.mutate has an extra option, detailedbelow.

Usage

mutate.huxtable(.data, ..., copy_cell_props = TRUE)

Arguments

.data

A huxtable.

...

Arguments passed todplyr::mutate().

copy_cell_props

Logical: copy cell and column properties from existingcolumns.

Details

Ifmutate creates new columns, and the argumentcopy_cell_propsis missing orTRUE, then cell and column properties will be copied fromexisting columns to their left, if there are any. Otherwise, they will be thestandard defaults. Row and table properties, and properties of cells inexisting columns, remain unchanged.

Examples

ht <- hux(a = 1:5, b = 1:5, c = 1:5, d = 1:5, add_colnames = FALSE)bold(ht)[c(1, 3), ] <- TRUEbold(ht)[, 1] <- TRUEht2 <- dplyr::select(ht, b:c)ht2bold(ht2)ht3 <- dplyr::mutate(ht, x = a + b)ht3bold(ht3)ht4 <- dplyr::mutate(ht,  x = a + b,  copy_cell_props = FALSE)bold(ht4)

Change how NA values are printed

Description

NA values in the huxtable are printed as the value ofna_string.

Usage

na_string(ht)na_string(ht) <- valueset_na_string(ht, row, col, value)map_na_string(ht, row, col, fn)

Arguments

ht

A huxtable.

value

A character vector or matrix. Set toNA to reset to the default, which is"".

row

A row specifier. Seerowspecs for details.

col

An optional column specifier.

fn

A mapping function. Seemapping-functions for details.

See Also

Other formatting functions:background_color(),bold(),font(),font_size(),number_format(),text_color()

Examples

jams[3, 2] <- NAjamsset_na_string(jams, "---")

Set how numbers are formatted in cells

Description

Ifnumber_format is:

Usage

number_format(ht)number_format(ht) <- valueset_number_format(ht, row, col, value)map_number_format(ht, row, col, fn)

Arguments

ht

A huxtable.

value

A character or integer vector,a list containing a function, orNA. Note that setting toNA does not reset to the default.

row

A row specifier. Seerowspecs for details.

col

An optional column specifier.

fn

A mapping function. Seemapping-functions for details.

Details

Number formatting is applied to any parts of cells that look like numbers.The exception is exponents inscientific notation; huxtable attempts to detect and ignore these.

The default value is "%.3g", which rounds numbers if they have more than 3significant digits, and which may use scientific notation for large numbers.

Note that if your cells are of type numeric, a number format ofNA doesn'tguarantee you get back what you typed in, since R's default conversion mayapply scientific notation and rounding.

To set number_format to a function, enclose the function inlist. The function shouldtake one argument and return a string.fmt_pretty() andfmt_percent()are useful shortcuts for common formatting functions.

See Also

fmt_pretty() andfmt_percent().options("huxtable.long_minus")inhuxtable-options for pretty-printing minus signs.

Other formatting functions:background_color(),bold(),font(),font_size(),na_string(),text_color()

Examples

ht <- huxtable(  number_format = c(    "Default",    "NA",    "2",    "\"%5.2f\"",    "Pretty",    "Sign"  ),  a = rep(1000, 6),  b = rep(1000.005, 6),  c = rep(0.0001, 6),  d = rep(-1, 6),  e = rep("3.2 (s.e. 1.4)", 6))number_format(ht)[3, -1] <- NAnumber_format(ht)[4, -1] <- 2number_format(ht)[5, -1] <- "%5.2f"number_format(ht)[6, -1] <- fmt_pretty()number_format(ht)[7, -1] <- list(  function(x) ifelse((x > 0), "+", "-"))right_border(ht) <- 1bottom_border(ht)[1, ] <- 1htht_bands <- huxtable("10000 Maniacs", autoformat = FALSE)# probably not what you want:ht_bands# fixed:set_number_format(ht_bands, NA)

Cell padding

Description

Functions to get or set the space around cell borders. Top, bottom, left andright padding all default to 6 points.

Usage

left_padding(ht)left_padding(ht) <- valueset_left_padding(ht, row, col, value)map_left_padding(ht, row, col, fn)right_padding(ht)right_padding(ht) <- valueset_right_padding(ht, row, col, value)map_right_padding(ht, row, col, fn)top_padding(ht)top_padding(ht) <- valueset_top_padding(ht, row, col, value)map_top_padding(ht, row, col, fn)bottom_padding(ht)bottom_padding(ht) <- valueset_bottom_padding(ht, row, col, value)map_bottom_padding(ht, row, col, fn)

Arguments

ht

A huxtable.

value

Numeric: padding width/height in points. Set toNA to reset to the default, which is6.

row

A row specifier. Seerowspecs for details.

col

An optional column specifier.

fn

A mapping function. Seemapping-functions for details.

See Also

set-multiple,set-outer.

Examples

left_padding(jams) <- 2left_padding(jams)jams <- set_left_padding(jams, 2)left_padding(jams)

Set the table's position with respect to surrounding content

Description

Table position may be "left", "right" or "center". If you want text towrap around the table, use "wrapleft" or "wrapright".

Usage

position(ht)position(ht) <- valueset_position(ht, value)

Arguments

ht

A huxtable.

value

String. "left", "center", "right", "wrapleft" or "wrapright". Set toNA to reset to the default, which is"center".

Details

"wrapleft" and"wrapright" position the table to the left or right, and allow text towrap around the table.

Value

property() returns the property value(s).set_property() andmap_property() return the modified huxtable.

Examples

set_position(jams, "left")set_position(jams, "right")set_position(jams, "center")

Format and print huxtables using a default method

Description

By default huxtables are printed usingprint_screen(). In certain cases, for examplein Sweave documents, it may beuseful to change this. You can do so by settingoptions("huxtable.print").

Usage

## S3 method for class 'huxtable'print(x, ...)## S3 method for class 'huxtable'format(x, ..., output = c("latex", "html", "md", "screen", "rtf", "typst"))

Arguments

x

A huxtable.

...

Options passed to other methods.

output

Output format. One of"html","latex","md","screen","rtf" or"typst".

Value

print prints the huxtable and returnsNULL invisibly.

format returns a string representation fromto_latex(),to_html() etc.

See Also

To change how huxtables are printed withinknitr, seeoptions("huxtable.knitr_output_format") inhuxtable-options

Examples

## Not run: # to print LaTeX output:options(huxtable.print = print_latex)# to print Typst output:options(huxtable.print = print_typst)## End(Not run)format(jams, output = "screen")format(jams, output = "md")format(jams, output = "typst")

Description

These functions print or return an HTML table.print_html also prepends a⁠<style>⁠ block defining basic CSS classes.

Usage

print_html(ht, ...)print_notebook(ht, ...)to_html(ht, ...)as_html(ht, ...)

Arguments

ht

A huxtable.

...

Arguments passed to methods. Not currently used.

Value

to_html returns an HTML string.as_html wrapsto_html and returns anhtmltools::HTML object.print_html prints the string and returnsNULL.

print_notebook prints HTML output suitable for use in anRStudio interactive notebook.

See Also

Other printing functions:print_latex(),print_md(),print_rtf(),print_screen(),print_typst()

Examples

ht <- hux(a = 1:3, b = letters[1:3])to_html(ht)as_html(ht)

Description

Create LaTeX representing a huxtable

Usage

print_latex(ht, ...)to_latex(ht, tabular_only = FALSE, ...)

Arguments

ht

A huxtable.

...

Arguments passed to methods.

tabular_only

Return only the LaTeX tabular, not the surrounding float.

Details

If we appear to be in a rmarkdown document with the Pandoc markdown+raw_attribute extensionavailable,to_latex will return LaTeX surrounded by a "raw attribute code block" (seehttps://pandoc.org/MANUAL.html#extension-raw_attribute). This helps protect against pandocaccidentally escaping the TeX code.

Value

to_latex returns a string.print_latex prints the string and returnsNULL.

See Also

Other printing functions:print_html(),print_md(),print_rtf(),print_screen(),print_typst()

Examples

ht <- huxtable(  a = 1:3,  b = letters[1:3])print_latex(ht)

Description

Create Markdown representing a huxtable

Usage

print_md(ht, ...)to_md(ht, header = TRUE, min_width = getOption("width")/4, max_width = 80, ...)

Arguments

ht

A huxtable.

...

Arguments passed to methods.

header

Logical. Print the first row as a header?

min_width

Minimum width in on-screen characters of the result.

max_width

Maximum width in on-screen characters of the result. Overridesmin_width.

Details

Onlyalign andcaption properties are used. The markdown format ismultiline_tables, see thepandoc documentation.

Value

to_md() returns a string.print_md() prints the string and returnsNULL.

See Also

Other printing functions:print_html(),print_latex(),print_rtf(),print_screen(),print_typst()

Examples

print_md(jams)

Description

These functions print or return an RTF character string.

Usage

print_rtf(ht, fc_tables = rtf_fc_tables(ht), ...)to_rtf(ht, fc_tables = rtf_fc_tables(ht), ...)

Arguments

ht

A huxtable.

fc_tables

Seertf_fc_tables().

...

Arguments passed to methods.

Details

RTF files use a single per-document table for colors, and one for fonts. If you are printingmultiple huxtables in a document, you need to make sure that the font and color table isset up correctly and that the RTF tables refer back to them. Seertf_fc_tables().

  1. Prepare all the huxtables;

  2. Callrtf_fc_tables(), passing in all the huxtables;

  3. Print thertfFCTables object in the RTF document header;

  4. Pass in thertfFCTables object to each call toprint_rtf.

Value

to_rtf returns a string representing an RTF table. Thefc_tables attribute of thereturned string will contain thefc_tables object that was passed in (or autocreated).print_rtf prints the string and returnsNULL.

Limitations

See Also

Other printing functions:print_html(),print_latex(),print_md(),print_screen(),print_typst()

Examples

print_rtf(jams)

Description

Print a huxtable on screen

Usage

print_screen(ht, ...)to_screen(  ht,  min_width = ceiling(getOption("width")/6),  max_width = getOption("width", Inf),  compact = TRUE,  colnames = TRUE,  color = getOption("huxtable.color_screen", default = TRUE),  ...)

Arguments

ht

A huxtable.

...

Passed on toto_screen.

min_width

Minimum width in on-screen characters of the result.

max_width

Maximum width in on-screen characters of the result. Overridesmin_width.

compact

Logical. To save space, don't print lines for empty horizontal borders.

colnames

Logical. Whether or not to print colum names.

color

Logical. Whether to print the huxtable in color (requires thecrayon package).

Details

Screen display shows the following features:

Cell padding, widths and heights are not shown.

Value

to_screen returns a string.print_screen prints the string and returnsNULL.

See Also

Other printing functions:print_html(),print_latex(),print_md(),print_rtf(),print_typst()

Examples

bottom_border(jams)[1, 1:2] <- 1bold(jams)[1, 1:2] <- TRUEjams <- map_text_color(  jams,  by_regex("berry" = "red"))print_screen(jams)

Description

These functions print or return a Typst table.

Usage

print_typst(ht, ...)to_typst(ht, ...)

Arguments

ht

A huxtable.

...

Arguments passed to methods. Not currently used.

Value

to_typst returns a Typst string.print_typst prints the string and returnsNULL.

See Also

Other printing functions:print_html(),print_latex(),print_md(),print_rtf(),print_screen()

Examples

ht <- huxtable(a = 1:3, b = letters[1:3])to_typst(ht)

Quickly print objects to a PDF, TeX, Typst, HTML, Microsoft Office or RTF document,or PNG or SVG images

Description

These functions use huxtable to print objects to an output document. They are usefulas one-liners for data reporting.

Usage

quick_latex(  ...,  file = confirm("huxtable-output.tex"),  borders = 0.4,  open = interactive())quick_pdf(  ...,  file = confirm("huxtable-output.pdf"),  borders = 0.4,  open = interactive(),  width = NULL,  height = NULL)quick_typst(  ...,  file = confirm("huxtable-output.typ"),  borders = 0.4,  open = interactive())quick_typst_pdf(  ...,  file = confirm("huxtable-output.pdf"),  borders = 0.4,  open = interactive(),  width = NULL,  height = NULL)quick_typst_png(  ...,  file = confirm_prefix("huxtable-output"),  borders = 0.4,  open = interactive(),  width = NULL,  height = NULL,  ppi = NULL)quick_typst_svg(  ...,  file = confirm_prefix("huxtable-output"),  borders = 0.4,  open = interactive(),  width = NULL,  height = NULL)quick_html(  ...,  file = confirm("huxtable-output.html"),  borders = 0.4,  open = interactive())quick_docx(  ...,  file = confirm("huxtable-output.docx"),  borders = 0.4,  open = interactive())quick_pptx(  ...,  file = confirm("huxtable-output.pptx"),  borders = 0.4,  open = interactive())quick_xlsx(  ...,  file = confirm("huxtable-output.xlsx"),  borders = 0.4,  open = interactive())quick_rtf(  ...,  file = confirm("huxtable-output.rtf"),  borders = 0.4,  open = interactive())

Arguments

...

One or more huxtables or R objects with anas_huxtable method.

file

File path for the output.

borders

Border width for members of... that are not huxtables.

open

Logical. Automatically open the resulting file?

width

String passed to the LaTeXgeometry package'spaperwidth option or Typst'spagewidth option. UseNULL for the default width.

height

String passed to the LaTeXgeometry package'spaperheight option or Typst'spageheight option. UseNULL for the default height.

ppi

Pixels per inch for PNG output.

Details

Objects in... will be converted to huxtables, with borders added.

If ‘file’ is not specified, the command will fail in non-interactive sessions. Ininteractive sessions, the default file path is "huxtable-output.xxx" in the working directory;if this already exists, you will be asked to confirm manually before proceeding.

To create docx and pptx filesflextable andofficer must be installed, while xlsxneedsopenxlsx.quick_typst_pdf(),quick_typst_png(), andquick_typst_svg() require thetypstcommand line tool.

quick_typst_pdf() with e.g.file = "foo.pdf" will overwrite and deletethe filefoo.typ.

quick_typst_png() andquick_typst_svg() create one image per huxtable. If there is more thanone object in..., images will have a numeric suffix like⁠"-1", "-2"⁠ etc.Existing files with the samefile prefix will be overwritten afterconfirmation in interactive sessions.

Value

InvisibleNULL.

Examples

## Not run: m <- matrix(1:4, 2, 2)quick_pdf(m, jams)quick_latex(m, jams)quick_typst(m, jams)quick_typst_pdf(m, jams)quick_typst_png(m, jams)quick_typst_svg(m, jams)quick_html(m, jams)quick_docx(m, jams)quick_xlsx(m, jams)quick_pptx(m, jams)quick_rtf(m, jams)## End(Not run)

Objects exported from other packages

Description

These objects are imported from other packages. Follow the linksbelow to see their documentation.

generics

glance,tidy


Manage LaTeX dependencies for huxtables

Description

report_latex_dependencies prints out and/or returns a list of LaTeX dependencies for addingto a LaTeX preamble.

check_latex_dependencies checks whether the required LaTeX packages are installed.

install_latex_dependencies is a utility function to install and/or updatethe LaTeX packages that huxtable requires. It callstinytex::tlmgr_install() if possible, or⁠tlmgr install⁠directly.

Usage

report_latex_dependencies(quiet = FALSE, as_string = FALSE)check_latex_dependencies(quiet = FALSE)install_latex_dependencies()

Arguments

quiet

Logical. Forreport_latex_dependencies, suppress printing of dependencies.Forcheck_latex_dependencies, suppress messages.

as_string

Logical: return dependencies as a string.

Value

Ifas_string isTRUE,report_latex_dependencies returns a string of"\\\\usepackage\\{...\\}" statements; otherwise it returns a list ofrmarkdown::latex_dependency objects, invisibly.

check_latex_dependencies() returnsTRUE orFALSE.

install_latex_dependencies returnsTRUE iftlmgr returns 0.

Examples

report_latex_dependencies()## Not run: check_latex_dependencies()## End(Not run)## Not run: install_latex_dependencies()## End(Not run)

Restack huxtables across/down the page

Description

Usage

restack_across(  ht,  rows,  headers = TRUE,  on_remainder = c("warn", "stop", "fill"))restack_down(  ht,  cols,  headers = TRUE,  on_remainder = c("warn", "stop", "fill"))

Arguments

ht

A huxtable

rows,cols

How many rows/columns the new result should have.

headers

Logical. Take account of header rows/columns?

on_remainder

String. "warn", "stop" or "fill". See below.

Details

Ifheaders isTRUE, header rows/columns will be repeated across/downthe restacked huxtable as necessary.

on_remainder determines what happens if the huxtable could not be evenlydivided for restacking:

Value

A new huxtable.

See Also

split-across-down

Examples

ht <- as_hux(matrix(LETTERS[1:4], 2, 2))ht <- set_all_borders(ht)htrestack_down(ht, 1)restack_across(ht, 1)# headers:restack_across(jams, 2)restack_across(jams, 2,  headers = FALSE)# on_remainder:restack_across(jams, 3,  on_remainder = "fill")

Rotate text within cells

Description

Numbers represent degrees to rotate text anti-clockwise:

Usage

rotation(ht)rotation(ht) <- valueset_rotation(ht, row, col, value)map_rotation(ht, row, col, fn)

Arguments

ht

A huxtable.

value

A numeric vector or matrix. Set toNA to reset to the default, which is0.

row

A row specifier. Seerowspecs for details.

col

An optional column specifier.

fn

A mapping function. Seemapping-functions for details.

Details

You will probably need to setcol_width() androw_height() explicitlyto achieve a nice result, in both HTML and LaTeX.

Examples

rotation(jams) <- 90rotation(jams)jams2 <- set_rotation(  jams,  270)rotation(jams2)jams3 <- set_rotation(  jams,  2:3, 1, 270)rotation(jams3)jams4 <- map_rotation(  jams,  by_rows(    270,    90  ))rotation(jams4)

Set the height of table rows

Description

Numeric heights are scaled to 1 and treated as proportions of the table heightin HTML, or of the text height (⁠\textheight⁠) in LaTeX. Characterrow heights must be valid CSS or LaTeX dimensions.

Usage

row_height(ht)row_height(ht) <- valueset_row_height(ht, row, value)

Arguments

ht

A huxtable.

value

Numeric or character vector. Set toNA to reset to the default,which is NA.

row

A row specifier. Seerowspecs for details.

Value

row_height() returns therow_height property.set_row_height() returns the modified huxtable.

See Also

col_width(),height(),width()

Other table measurements:col_width(),height(),width()

Examples

row_height(jams) <- c(.4, .2, .2, .2)row_height(jams)

Different ways to select rows and columns

Description

This help page describes how to use therow andcol arguments in⁠set_*⁠ functions.

The basics

The⁠set_*⁠ functions for cell properties all have arguments like this:set_property(ht, row, col, value).

You can treatrow andcol arguments like arguments fordata frame subsetting. For example, you can userow = 1:3 to get thefirst three rows,col = "salary" to specify the column named "salary", orrow = ht$salary >= 50000 to specify rows where a condition is true.

There are also a few extra tricks you can use:

The gory details

How the row and col arguments are parsed depends on the number of arguments passed to the⁠set_*⁠function.

Examples

set_bold(jams, 2:4, 1:2, TRUE)set_background_color(  jams, evens, everywhere,  "grey95")set_bold(  jams, everywhere,  tidyselect::matches("yp"), TRUE)set_text_color(  jams, 2:4, 1:2,  c("red", "violetred", "purple"))

Create RTF font and color tables

Description

Create RTF font and color tables

Usage

rtf_fc_tables(..., extra_fonts = "Times", extra_colors = character(0))

Arguments

...

One or more objects of classhuxtable.

extra_fonts

Extra fonts to include. These will be first in the fonts table.

extra_colors

Extra colors to include, as R color names.

Details

RTF documents have a single table of fonts, and a table of colors, in the RTF header. Tocreate font and color tables for multiple huxtables, use this command. You canprint thereturned object in the RTF header. Pass it toprint_rtf() orto_rtf() to ensure thathuxtables print out the correct colour references.

Value

An object of classrtfFCTables. This is a list containing two items:"fonts"is a character vector of unique font names;"colors" is a character vector of unique colornames.

Examples

# Printing multiple huxtables:ht <- huxtable("Blue with red border")ht <- set_all_borders(ht, 1)ht <- set_all_border_colors(ht, "red")background_color(ht) <- "blue"ht2 <- huxtable("Dark green text")text_color(ht2) <- "darkgreen"fc_tbls <- rtf_fc_tables(ht, ht2)# In the document header:print(fc_tbls)# In the document body:print_rtf(ht, fc_tables = fc_tbls)print_rtf(ht2, fc_tables = fc_tbls)

Escape text for various formats

Description

This escapes a string for LaTeX, HTML, Typst or RTF.

Usage

sanitize(str, type = c("latex", "html", "typst", "rtf"))

Arguments

str

A character object.

type

"latex","html","typst" or"rtf".

Details

HTML and LaTeX code was copied over fromxtable::sanitize().

Value

The sanitized character object.

Examples

txt <- "Make $$$ with us"sanitize(txt, type = "latex")

Set left, right, top and bottom properties

Description

These functions set left, right,top and/or bottom propertiessimultaneously for the specified cells.

Usage

set_all_borders(ht, row, col, value = 0.4)map_all_borders(ht, row, col, fn)set_all_border_colors(ht, row, col, value)map_all_border_colors(ht, row, col, fn)set_all_border_styles(ht, row, col, value)map_all_border_styles(ht, row, col, fn)set_all_padding(ht, row, col, value)map_all_padding(ht, row, col, fn)set_tb_padding(ht, row, col, value)map_tb_padding(ht, row, col, fn)set_lr_padding(ht, row, col, value)map_lr_padding(ht, row, col, fn)set_tb_borders(ht, row, col, value)map_tb_borders(ht, row, col, fn)set_lr_borders(ht, row, col, value)map_lr_borders(ht, row, col, fn)set_tb_border_colors(ht, row, col, value)map_tb_border_colors(ht, row, col, fn)set_lr_border_colors(ht, row, col, value)map_lr_border_colors(ht, row, col, fn)set_tb_border_styles(ht, row, col, value)map_tb_border_styles(ht, row, col, fn)set_lr_border_styles(ht, row, col, value)map_lr_border_styles(ht, row, col, fn)

Arguments

ht

A huxtable.

row

A row specifier. Seerowspecs for details.

col

An optional column specifier.

value

Value(s) to set. Set toNA to reset to the default.

fn

A mapping function. Seemapping-functions for details.

Details

Value

The modified huxtable.

See Also

borders,border-colors,border-styles,padding.

Examples

ht <- as_hux(jams)ht <- set_all_borders(ht)htht <- set_all_border_colors(ht, "red")htht <- set_all_border_styles(ht, "double")ht <- set_all_padding(ht, 1:3, 1:2, "20px")ht <- set_tb_padding(ht, 10)ht <- set_tb_borders(ht)set_tb_border_colors(ht, "red")set_tb_border_styles(ht, "double")

Set borders and padding around a rectangle of cells

Description

Set borders and padding around a rectangle of cells

Usage

set_outer_borders(ht, row, col, value = 0.4)set_outer_border_colors(ht, row, col, value)set_outer_border_styles(ht, row, col, value)set_outer_padding(ht, row, col, value)

Arguments

ht

A huxtable.

row

A row specifier. Seerowspecs for details.

col

An optional column specifier.

value

Border width, color, style or abrdr() object. Seeborders.For padding, padding width in points.

Details

set_outer_borders sets borders round the top, bottom, left andright of a group of cells. Behaviour is undefined unlessrow andcolspecify contiguous sequences.set_outer_border_colors andset_outer_border_styles set border colors and styles.set_outer_paddingsets padding, i.e. top padding on the top row of cells, etc.

Examples

ht2 <- huxtable(a = 1:3, b = 1:3)set_outer_borders(ht2)set_outer_borders(ht2, 2:3, 1:2)

Set cell contents

Description

set_contents() is a convenience function to change the cell contents of a huxtable withina dplyr chain.set_contents(ht, x, y, foo) just callsht[x, y] <- foo and returnsht.

Usage

contents(ht)contents(ht) <- valueset_contents(ht, row, col, value)map_contents(ht, row, col, fn)

Arguments

ht

A huxtable.

value

Cell contents.

row

A row specifier. Seerowspecs for details.

col

An optional column specifier.

fn

A mapping function. Seemapping-functions for details.

Examples

data(jams)set_contents(jams, 2, 1, "Blackcurrant")map_contents(jams, by_regex(".*berry" = "Snodberry"))

Default huxtable properties

Description

Defaults are used for new huxtables, and also when a property is set toNA.

Usage

set_default_properties(...)get_default_properties(names = NULL)

Arguments

...

Properties specified by name, or a single named list.

names

Vector of property names. IfNULL, all properties are returned.

Details

Note thatautoformat = TRUE inhuxtable() overrides some defaults.

To set default border styles, use the pseudo-propertiesborder/border_style/border_color. You cannot set defaults separately fordifferent sides.

Value

Forset_default_properties, a list of the previous property values, invisibly.

Forget_default_properties, a list of the current defaults.

See Also

Options for autoformat inhuxtable-options.

Examples

old <- set_default_properties(  text_color = "red",  border     = 0.4)hux(a = 1:2, b = 1:2)set_default_properties(old)get_default_properties("bold")

Set cell contents, interpreting them as markdown

Description

This convenience function callsset_contents() andset_markdown().

Usage

set_markdown_contents(ht, row, col, value)

Arguments

ht

A huxtable.

row

A row specifier. Seerowspecs for details.

col

An optional column specifier.

value

Cell contents, as a markdown string.

Value

The modified huxtable.

Note

Markdown content in cells is completely separate from printing the wholetable as markdown usingprint_md(). When you setmarkdown toTRUE,huxtable itself interprets the cell contents as markdown, and spits out HTML,TeX or whatever.

See Also

markdown().

Examples

set_markdown_contents(  jams, 1, 1,  "**Type** of jam")

Section about colspan/rowspan

Description

Section about colspan/rowspan

Cell content

In merged cell ranges, only the top left cell's content is displayed.In addition, when you merge cells (either by settingcolspan() orrowspan(), or usingmerge_cells() and friends) the content of the topleft cell is copied to other cells. This prevents unexpected changes tocontent if you reorder or subset rows and columns.


Extend cells over multiple rows and/or columns

Description

A cell with rowspan of 2 covers the cell directly below it. A cell withcolspan of 2 covers the cell directly to its right. A cell with rowspan of 2and colspan of 2 covers a 2 x 2 square, hiding three other cells.

Usage

rowspan(ht)rowspan(ht) <- valueset_rowspan(ht, row, col, value)map_rowspan(ht, row, col, fn)colspan(ht)colspan(ht) <- valueset_colspan(ht, row, col, value)map_colspan(ht, row, col, fn)

Arguments

ht

A huxtable.

value

An integer vector or matrix.

row

A row specifier. Seerowspecs for details.

col

An optional column specifier.

fn

A mapping function. Seemapping-functions for details.

Cell content

In merged cell ranges, only the top left cell's content is displayed.In addition, when you merge cells (either by settingcolspan() orrowspan(), or usingmerge_cells() and friends) the content of the topleft cell is copied to other cells. This prevents unexpected changes tocontent if you reorder or subset rows and columns.

See Also

merge_cells(),merge_across() andmerge_down() fora higher-level interface.

Examples

letter_hux <- as_hux(matrix(LETTERS[1:9], 3, 3))letter_hux <- set_all_borders(letter_hux)letter_huxset_rowspan(letter_hux, 1, 1, 2)set_colspan(letter_hux, 1, 1, 2)

Split a huxtable into multiple huxtables

Description

These functions split a huxtable horizontally or vertically, andreturn the new sub-tables in a list.

Usage

split_across(ht, after, height, headers = TRUE)split_down(ht, after, width, headers = TRUE)

Arguments

ht

A huxtable.

after

Rows/columns after which to split. Seerowspecs for details.Note thattidyselect semantics are allowedinsplit_down() but notsplit_across().

height,width

Maximum height/width for the result.

headers

Logical. Take account of header rows/columns?

Details

Only one ofafter andwidth orheight must be given. Ifwidth orheight is given, the huxtable will be split bycol_width() orrow_height(), which must be numeric with noNA values.

Ifheaders isTRUE, all previous headers will be added to eachnew table.

Value

A list of huxtables.

See Also

restack-across-down

Examples

ht <- as_hux(matrix(LETTERS[1:16], 4, 4))ht <- set_all_borders(ht)split_across(ht, after = 2)split_down(ht, after = c(1, 3))col_width(ht) <- c(0.15, 0.1, 0.25, 0.3)split_down(ht, width = 0.3)# split by column name:split_down(jams, "Type")# headers are repeated:split_across(jams, 3)

Return every n row or column numbers

Description

This is a convenience function to use in row or column specifications.In this context,stripe(n, from) will return⁠from, from + n, ...,⁠ up to the number of rowsor columns of the huxtable.evens andodds return even and oddnumbers, i.e. they are equivalent tostripe(2, 2) andstripe(2, 1) respectively.everywhere returns all rows or columns, equivalently tostripe(1).

Usage

stripe(n = 1, from = n)everywhere(ht, dimension)evens(ht, dimension)odds(ht, dimension)

Arguments

n

A number (at least 1)

from

A number (at least 1)

ht

An object with adim attribute like a matrix or data frame.

dimension

Number of the dimension to use.

Details

Technically,stripe returns a 2-argument function which can be called likef(ht, dimension). Seerowspecs for details.

Until huxtable 5.0.0,stripe was calledevery. It was renamed toavoid a clash withpurrr::every.

Examples

ht <- huxtable(a = 1:10, b = 1:10)set_background_color(  ht,  evens, everywhere,  "grey95")set_background_color(  ht,  stripe(3), everywhere,  "grey95")

Set background color stripes

Description

These convenience functions callmap_background_color withby_rowsorby_cols.

Usage

stripe_rows(ht, stripe1 = "white", stripe2 = "grey90")stripe_columns(ht, stripe1 = "white", stripe2 = "grey90")

Arguments

ht

A huxtable.

stripe1

Color for rows/columns 1, 3, 5, ...

stripe2

Color for rows/columns 2, 4, 6, ...

Examples

stripe_rows(jams)stripe_columns(jams)stripe_rows(jams, "red", "blue")

Set multiple properties on headers

Description

These functions set arbitrary cell properties on cells in header rowsand/or columns.

Usage

style_headers(ht, ...)style_header_rows(ht, ...)style_header_cols(ht, ...)style_cells(ht, row, col, ...)set_cell_properties(ht, row, col, ...)

Arguments

ht

A huxtable.

...

Named list of cell properties.

row

A row specifier. Seerowspecs for details.

col

An optional column specifier.

Details

set_cell_properties is a deprecated alias forstyle_cells. Don't use it.

Examples

style_headers(jams, text_color = "red")jams <- set_header_cols(jams, 1, TRUE)style_header_cols(jams,  text_color = c(    NA, "red",    "darkred", "purple"  ))style_cells(jams, everywhere, 2, bold = TRUE)

Transpose a huxtable

Description

t() switches a huxtable so rows become columns and columns become rows.

Usage

## S3 method for class 'huxtable't(x)

Arguments

x

A huxtable.

Details

Row and column spans ofx will be swapped, as will column widths and row heights,table width and height, and cell borders (bottom becomes right, etc.).Other properties - in particular, alignment, vertical alignment and rotation - will bepreserved.

Value

The transposed huxtable.

Examples

ht <- huxtable(  a = 1:3,  b = letters[1:3],  autoformat = FALSE)bottom_border(ht)[3, ] <- 1htt(ht)

Set the "table" environment in LaTeX

Description

By default this is"table".

Usage

table_environment(ht)table_environment(ht) <- valueset_table_environment(ht, value)

Arguments

ht

A huxtable.

value

A string. Set toNA to reset to the default, which is"table".

Details

No features are guaranteed to work if you set this to a non-defaultvalue. Use at your own risk! In particular, you may need to setlatex_float() to a non-default value.

Ifposition() is set to"wrapleft" or"wrapright", thisvalue is overridden.

Value

property() returns the property value(s).set_property() andmap_property() return the modified huxtable.

Examples

set_table_environment(jams, "table*")

Set the table's tabular environment in LaTeX

Description

By default this is either"tabular" or"tabularx".

Usage

tabular_environment(ht)tabular_environment(ht) <- valueset_tabular_environment(ht, value)

Arguments

ht

A huxtable.

value

A string. Set toNA to reset to the default, which isNA_character_.

Details

No features are guaranteed to work if you set this to a non-defaultvalue. Use at your own risk!

Value

property() returns the property value(s).set_property() andmap_property() return the modified huxtable.

Examples

set_tabular_environment(jams, "longtable")

Set the color of text in cells

Description

Colors can be in any format understood by R:

Usage

text_color(ht)text_color(ht) <- valueset_text_color(ht, row, col, value)map_text_color(ht, row, col, fn)

Arguments

ht

A huxtable.

value

A character vector or matrix. Set toNA to reset to the default, which isNA_character_.

row

A row specifier. Seerowspecs for details.

col

An optional column specifier.

fn

A mapping function. Seemapping-functions for details.

See Also

Other formatting functions:background_color(),bold(),font(),font_size(),na_string(),number_format()

Examples

text_color(jams) <- "blue"text_color(jams)set_text_color(jams, "red")set_text_color(jams, 2:3, 1, "red")map_text_color(jams, by_rows("red", "blue"))

Theme a huxtable

Description

These functions quickly set default styles for a huxtable.

Usage

theme_plain(ht, header_rows = TRUE, position = "center")theme_bright(  ht,  header_rows = TRUE,  header_cols = FALSE,  colors = c("#7eabf2", "#e376e3", "#fcbb03", "#7aba59", "#fc0356"))theme_basic(ht, header_rows = TRUE, header_cols = FALSE)theme_compact(ht, header_rows = TRUE, header_cols = FALSE)theme_striped(  ht,  stripe = "grey90",  stripe2 = "grey95",  header_rows = TRUE,  header_cols = TRUE)theme_grey(ht, header_rows = TRUE, header_cols = TRUE)theme_blue(ht, header_rows = TRUE, header_cols = TRUE)theme_orange(ht, header_rows = TRUE, header_cols = TRUE)theme_green(ht, header_rows = TRUE, header_cols = TRUE)theme_article(ht, header_rows = TRUE, header_cols = TRUE)theme_mondrian(ht, prop_colored = 0.1, font = NULL)

Arguments

ht

A huxtable object.

header_rows

Logical: style header rows?

position

"left", "center" or "right"

header_cols

Logical: style header columns?

colors

Colors for header rows. Can also be a palette function.

stripe

Background colour for odd rows

stripe2

Background colour for even rows

prop_colored

Roughly what proportion of cells should havea primary-color background?

font

Font to use. For LaTeX, try"cmss".

Details

Value

The huxtable object, appropriately styled.

Examples

theme_plain(jams)theme_basic(jams)theme_compact(jams)theme_striped(jams)theme_article(jams)theme_bright(jams)theme_grey(jams)theme_blue(jams)theme_orange(jams)theme_green(jams)theme_mondrian(jams)

Change a model'stidy output

Description

Usetidy_override andtidy_replace to provide your own p values,confidence intervals etc. for a model.

Usage

tidy_override(x, ..., glance = list(), extend = FALSE)tidy_replace(x, tidied, glance = list())## S3 method for class 'tidy_override'tidy(x, ...)## S3 method for class 'tidy_override'glance(x, ...)## S3 method for class 'tidy_override'nobs(object, ...)

Arguments

x

A model with methods defined forgenerics::tidy() and/orgenerics::glance().

...

Intidy_override, columns of statistics to replacetidy output. Intidy andglance methods, arguments passed on to the underlying model.

glance

A list of summary statistics forglance.

extend

Logical: allow adding new columns totidy(x) andglance(x)?

tidied

Data frame to replace the result oftidy(x).

object

Atidy_override object.

Details

tidy_override allows you to replace some columns oftidy(x) with your owndata.

tidy_replace allows you to replace the result oftidy(x) entirely.

Value

An object that can be passed in tohuxreg.

Examples

if (!requireNamespace("broom", quietly = TRUE)) {  stop("Please install 'broom' to run this example.")}lm1 <- lm(mpg ~ cyl, mtcars)fixed_lm1 <- tidy_override(lm1,  p.value = c(.04, .12),  glance = list(r.squared = 0.99))huxreg(lm1, fixed_lm1)if (requireNamespace("nnet", quietly = TRUE)) {  mnl <- nnet::multinom(gear ~ mpg, mtcars)  tidied <- broom::tidy(mnl)  mnl4 <- tidy_replace(mnl, tidied[tidied$y.level == 4, ])  mnl5 <- tidy_replace(mnl, tidied[tidied$y.level == 5, ])  huxreg(mnl4, mnl5, statistics = "nobs")}

Set the vertical alignment of cell content

Description

Allowed values are "top", "middle", "bottom" orNA.

Usage

valign(ht)valign(ht) <- valueset_valign(ht, row, col, value)map_valign(ht, row, col, fn)

Arguments

ht

A huxtable.

value

A character vector or matrix. Set toNA to reset to the default, which is"top".

row

A row specifier. Seerowspecs for details.

col

An optional column specifier.

fn

A mapping function. Seemapping-functions for details.

Details

Vertical alignment may not work for short text in LaTeX.Defining row heights withrow_height() may help.

Examples

valign(jams) <- "top"valign(jams)jams2 <- set_valign(jams, "bottom")valign(jams2)jams3 <- set_valign(jams, 2:3, 1, "bottom")valign(jams3)jams4 <- map_valign(jams, by_rows(  "bottom",  "top"))valign(jams4)

Set the table width

Description

width() sets the width of the entire table, whilecol_width() sets thewidth of individual columns. A numeric width is treated as a proportion off the surrounding block width (HTML) or text width (LaTeX). A character widthmust be a valid CSS or LaTeX dimension.

Usage

width(ht)width(ht) <- valueset_width(ht, value)

Arguments

ht

A huxtable.

value

A number or string. Set toNA to reset to the default, which isNA_real_.

Value

property() returns the property value(s).set_property() andmap_property() return the modified huxtable.

See Also

Other table measurements:col_width(),height(),row_height()

Examples

set_width(jams, 0.8)

Wrap cell content over multiple lines

Description

Text wrapping only works when the tablewidth() has been set. Inparticular, if you want to insert newlines in cells, then you shouldset a value forwidth() and setwrap toTRUE.

Usage

wrap(ht)wrap(ht) <- valueset_wrap(ht, row, col, value)map_wrap(ht, row, col, fn)

Arguments

ht

A huxtable.

value

A logical vector or matrix. Set toNA to reset to the default, which isTRUE.

row

A row specifier. Seerowspecs for details.

col

An optional column specifier.

fn

A mapping function. Seemapping-functions for details.

Examples

long_text <- paste(  rep("Some long text.", 10),  collapse = " ")ht <- huxtable(Long = long_text)width(ht) <- 0.2wrap(ht) <- TRUE## Not run: quick_html(ht)## End(Not run)

[8]ページ先頭

©2009-2025 Movatter.jp