### Install flextable from GitHub Source: https://github.com/davidgohel/flextable/blob/main/README.md Command to install the development version of the flextable package directly from its GitHub repository using the devtools package. ```r devtools::install_github("davidgohel/flextable") ``` -------------------------------- ### Install Pandoc Separately Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/errors.md Alternatively, install Pandoc from pandoc.org to resolve PDF export errors. ```r # Or install Pandoc separately from pandoc.org ``` -------------------------------- ### Install flextable from CRAN Source: https://github.com/davidgohel/flextable/blob/main/README.md Standard command to install the flextable package from the Comprehensive R Archive Network (CRAN). ```r install.packages("flextable") ``` -------------------------------- ### Install Quarto Markdown Extension Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/advanced-utilities.md Installs the flextable Quarto extension for enhanced rendering in Quarto documents. This function is called invisibly and installs the extension to your Quarto project. ```r install_flextable_quarto_extension() ``` -------------------------------- ### install_flextable_quarto_extension() Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/advanced-utilities.md Installs the flextable Quarto markdown extension, which enhances the rendering capabilities of flextable objects within Quarto documents. ```APIDOC ## install_flextable_quarto_extension() ### Description Install Quarto markdown extension. This function installs the flextable Quarto extension for enhanced rendering in Quarto documents. ### Signature ```r install_flextable_quarto_extension() ``` ### Return Value Invisible: NULL. Installs extension to Quarto project. ### Details Installs the flextable Quarto extension for enhanced rendering in Quarto documents. ``` -------------------------------- ### Render Flextable as Image with webshot2 Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/errors.md Install the webshot2 package to enable rendering flextables as images using as_image(). ```r ft <- flextable(head(iris)) img <- as_image(ft, format = "png") # Error if webshot2 not installed ``` ```r install.packages("webshot2") ``` -------------------------------- ### Install TinyTeX for PDF Export Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/errors.md Install TinyTeX to resolve "Pandoc version ... is not available" errors when exporting to PDF. ```r tinytex::install_tinytex() ``` -------------------------------- ### Set and Reset Flextable Defaults Example Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/configuration.md Demonstrates setting custom defaults and then resetting them to factory settings. After resetting, new flextables will use the factory configuration. ```r # Set custom defaults set_flextable_defaults(font.size = 14, theme_fun = theme_zebra) # Later, reset to defaults init_flextable_defaults() # Now new flextables use factory settings ft <- flextable(head(iris)) ``` -------------------------------- ### R Markdown Setup for Flextable Defaults Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/configuration.md Configures flextable defaults within an R Markdown document's setup chunk to ensure consistent styling for all subsequent tables. ```r --- title: "My Report" --- {r setup, include=FALSE} library(flextable) set_flextable_defaults( font.size = 11, theme_fun = theme_booktabs, padding = 5 ) # All tables below use these defaults {r table1} flextable(head(iris)) {r table2} flextable(head(mtcars)) ``` -------------------------------- ### Installing Flextable-qmd Lua Filter Source: https://github.com/davidgohel/flextable/blob/main/NEWS.md Use `use_flextable_qmd()` to install the companion 'flextable-qmd' Lua filter extension in your Quarto project. This enables the embedding of Quarto markdown within flextable cells. ```R library(flextable) # Install the flextable-qmd Lua filter use_flextable_qmd() ``` -------------------------------- ### Select Columns by Formula Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/README.md Demonstrates selecting columns based on a formula that evaluates column properties, such as data type. The `is.numeric(.)` example selects all numeric columns. ```r # Select by formula (on column classes) bold(ft, j = ~ is.numeric(.)) # All numeric columns ``` -------------------------------- ### Create Flextable from Data Frame Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/README.md Demonstrates how to create a flextable object from a data frame using the `flextable()` function. This is the most common way to start building a table. ```r library(flextable) # Create from data frame ft <- flextable(head(iris)) ``` -------------------------------- ### Get Flextable as HTML or LaTeX String Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/README.md Demonstrates how to get the flextable content as raw HTML or LaTeX strings using `as_html()` and `to_latex()`. This is useful for embedding tables in web pages or other LaTeX documents. ```r # Or get output for embedding html <- as_html(ft) latex <- to_latex(ft) ``` -------------------------------- ### Export Flextable to Various Formats Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/README.md Provides examples of exporting a flextable to common document formats like DOCX, PPTX, and HTML using dedicated save functions. This is essential for report generation. ```r # To various formats save_as_docx(ft, path = "table.docx") save_as_pptx(ft, path = "table.pptx") save_as_html(ft, path = "table.html") ``` -------------------------------- ### Compose flextable with an image Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/content-composition.md Use `compose` with `as_image` to insert an image into a table cell. This example places an image in the first cell of the first row. ```r ft <- flextable(head(iris)) # Create a sample image png_file <- file.path(tempdir(), "image.png") # (assumes image file exists) ft <- compose(ft, j = 1, i = 1, value = as_paragraph(as_image(png_file, width = 0.5, height = 0.5)) ) ``` -------------------------------- ### Gradient Coloring with highlight() Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/formatting-styles.md Apply gradient coloring to text based on column values using a function with highlight(). The function receives column values and returns color values. This example colors 'mpg' based on quantiles. ```r gradient_fun <- function(x) { scales::col_quantile(palette = c("white", "red"), domain = NULL)(x) } ft <- highlight(ft, j = "mpg", color = gradient_fun, source = "mpg") ``` -------------------------------- ### Apply Multiple Formatting Properties with style() Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/formatting-styles.md Use the `style()` function to set text, paragraph, and cell formatting properties on a selection of cells. This is useful when multiple formatting types need to be applied at once, for example, to the header of a flextable. ```r library(officer) ft <- flextable(head(mtcars)) # Define formatting cell_border <- fp_cell(border = fp_border(color = "black")) par_center <- fp_par(text.align = "center") text_red <- fp_text(color = "red", bold = TRUE) # Apply to selection ft <- style(ft, i = 1:2, j = 1:3, pr_t = text_red, pr_p = par_center, pr_c = cell_border, part = "header" ) ``` -------------------------------- ### Create a basic flextable Source: https://github.com/davidgohel/flextable/blob/main/README.md Shows how to create a simple flextable from the head of the airquality dataset. Requires the flextable library to be loaded. ```r library(flextable) flextable(head(airquality)) ``` -------------------------------- ### Get Table Dimensions - dim() Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/table-structure.md Use `dim()` to get the dimensions of a flextable object, returning a numeric vector with the number of rows and columns. This provides a quick overview of the table's size. ```r ft <- flextable(head(iris)) dim(ft) # 6 5 ``` -------------------------------- ### Flextable Default Application Order Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/configuration.md Demonstrates the order in which flextable defaults are applied and overridden by local formatting. Set global defaults, create a flextable, and then apply local formatting to observe the hierarchy. ```r # 1. Set global defaults set_flextable_defaults( font.size = 12, color = "blue" ) # 2. Create flextable (applies defaults + theme) ft <- flextable(head(iris)) # At this point: all text is blue, 12pt # 3. Apply local formatting (overrides defaults) ft <- color(ft, i = 1, color = "red") # Now: row 1 is red 12pt, rest is blue 12pt ``` -------------------------------- ### Set Global Flextable Defaults Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/README.md Shows how to set default options for all subsequent flextables created in the session using `set_flextable_defaults()`. This includes font size, theme, and padding. ```r # Or set defaults before creating tables set_flextable_defaults( font.size = 11, theme_fun = theme_booktabs, padding = 5 ) ``` -------------------------------- ### dim() Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/table-structure.md Gets the dimensions (number of rows and columns) of a flextable object. ```APIDOC ## dim() ### Description Get flextable dimensions ### Signature ```r dim(x) ``` ### Parameters #### Parameters - `x` (flextable) - A flextable object ### Return Value A numeric vector: `c(n_rows_in_body, n_cols)`. ### Examples ```r ft <- flextable(head(iris)) dim(ft) # 6 5 ``` ``` -------------------------------- ### Create and save a flextable to DOCX Source: https://github.com/davidgohel/flextable/blob/main/README.md Demonstrates how to create a flextable from the mtcars dataset, apply a theme, and save it as a DOCX file. ```r flextable(mtcars) |> theme_vanilla() |> save_as_docx(path = "mytable.docx") ``` -------------------------------- ### Get Number of Columns - ncol_keys() Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/table-structure.md Use `ncol_keys()` to retrieve the number of columns in a flextable object. This function is useful for understanding the width of your table. ```r ft <- flextable(head(iris)) ncol_keys(ft) # 5 ``` -------------------------------- ### Remove All Borders from Flextable Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/borders-and-merging.md Use `border_remove()` to remove all existing borders from a flextable. This is useful for starting with a clean slate or when a borderless table is desired. ```r ft <- flextable(head(mtcars)) ft <- theme_box(ft) # Apply borders ft <- border_remove(ft) # Remove all borders ``` -------------------------------- ### Create Formatted Text Chunk Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/content-composition.md Illustrates creating a text chunk with specific formatting properties, such as color and bold text, using the as_chunk() function for use within as_paragraph(). ```r library(officer) ft <- flextable(head(iris)) ft <- compose(ft, j = "Sepal.Length", value = as_paragraph( "Sepal.Length: ", as_chunk(Sepal.Length, props = fp_text(color = "red", bold = TRUE)) ) ) ``` -------------------------------- ### Create flextable from summarized data Source: https://github.com/davidgohel/flextable/blob/main/README.md Demonstrates converting summarized data (from diamonds dataset) into a flextable with the first column spread. ```r ggplot2::diamonds[, c("cut", "carat", "price", "clarity", "table")] |> summarizor(by = c("cut")) |> as_flextable(spread_first_col = TRUE) ``` -------------------------------- ### Robust Flextable Creation with tryCatch Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/errors.md Use tryCatch to gracefully handle potential errors during flextable creation and autofitting. Errors are caught, a warning is issued, and NULL is returned. ```r result <- tryCatch({ ft <- flextable(data) ft <- autofit(ft) ft }, error = function(e) { warning(sprintf("Failed to create flextable: %s", e$message)) NULL }) ``` -------------------------------- ### Get Default Text Formatting Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/advanced-utilities.md Retrieves the default `fp_text` object used for new flextables. This represents the factory default text properties before any custom formatting is applied. ```r fp_text_default() ``` -------------------------------- ### Create Flextable from Model Object Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/README.md Shows how to convert statistical model outputs, such as linear models, into a flextable using the `as_flextable()` function. This is useful for presenting model summaries. ```r # Create from model or other object ft <- as_flextable(lm(Sepal.Length ~ Sepal.Width, iris)) ``` -------------------------------- ### Set Header Background Color Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/formatting-styles.md Use the bg() function to set a fixed background color for table header cells. This example sets the header background to 'lightblue'. ```r ft <- flextable(head(mtcars)) # Fixed background ft <- bg(ft, bg = "lightblue", part = "header") ``` -------------------------------- ### Apply Multiple Formatting Properties Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/README.md Demonstrates applying multiple formatting properties simultaneously to a flextable using the `style()` function. This allows for setting text properties, paragraph alignment, and cell background in one call. ```r # Multiple properties at once ft <- style(ft, i = 1, part = "header", pr_t = fp_text(bold = TRUE, size = 12), pr_p = fp_par(text.align = "center"), pr_c = fp_cell(background = "lightgray") ) ``` -------------------------------- ### Apply Fixed Color to Flextable Cells Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/formatting-styles.md Use the color() function to apply a fixed color to selected cells in a flextable. This example sets the first row to red. ```r ft <- flextable(head(mtcars)) # Fixed color ft <- color(ft, color = "red", i = 1) ``` -------------------------------- ### Apply Built-in Theme Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/README.md Demonstrates applying a pre-defined theme, such as `theme_booktabs()`, to a flextable for professional styling. Themes control borders, colors, and fonts. ```r # Apply theme ft <- theme_booktabs(ft) ``` -------------------------------- ### Compose flextable with colored text Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/content-composition.md Use `compose` with `colorize` to add colored text to specific cells. This example adds a red 'Note:' prefix to the 'Sepal.Length' column. ```r ft <- flextable(head(iris)) ft <- compose(ft, j = "Sepal.Length", value = as_paragraph( colorize("Note: ", color = "red"), as_chunk(Sepal.Length) ) ) ``` -------------------------------- ### Render flextable as PNG image Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/export-and-output.md Use the `as_image` function to render a flextable as a PNG image. Specify the desired width and format. ```r ft <- flextable(head(iris)) # Render as PNG img <- as_image(ft, width = 6, format = "png") ``` -------------------------------- ### Get Number of Rows in Flextable Part Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/table-structure.md Retrieve the number of rows for a specific part of a flextable (header, body, or footer). Useful for understanding the dimensions of different table sections. ```r ft <- flextable(head(iris)) nrow_part(ft, "body") # 6 nrow_part(ft, "header") # 1 nrow_part(ft, "footer") # 0 ``` -------------------------------- ### theme_vanilla() Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/sizing-and-themes.md Applies the vanilla theme to a flextable, providing minimal styling suitable as a base for custom themes. ```APIDOC ## theme_vanilla() ### Description Applies vanilla theme (minimal styling) to a flextable object. ### Signature ```r theme_vanilla(x) ``` ### Parameters #### Path Parameters - **x** (flextable) - A flextable object ### Return Value The modified flextable object with vanilla theme applied. ### Details Applies minimal styling: simple borders, default fonts. A good starting point for custom styling. ``` -------------------------------- ### R: Use Values, Not Functions, in as_chunk Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/errors.md This error occurs when passing a function directly to `as_chunk` within `compose`. You must pass a value or call the function to get a value. ```r ft <- flextable(head(iris)) ft <- compose(ft, j = 1, value = as_paragraph(as_chunk(mean)) # Error: function not allowed ) ``` ```r ft <- compose(ft, j = 1, value = as_paragraph(as_chunk(mean(Sepal.Length))) ) ``` -------------------------------- ### Applying a Minimal Theme with No Borders Source: https://github.com/davidgohel/flextable/blob/main/NEWS.md Use the `theme_borderless()` function to apply a theme with no borders, a bold header, and standard column alignment. ```R library(flextable) theme_borderless(my_flextable) ``` -------------------------------- ### Get Current Flextable Defaults Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/configuration.md Retrieve the current global default formatting properties. This is useful for inspecting active defaults or creating custom defaults based on existing ones. ```r defaults <- get_flextable_defaults() print(defaults) defaults$font.size ``` -------------------------------- ### Apply Vanilla Theme to Flextable Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/sizing-and-themes.md Use theme_vanilla() for minimal styling, providing a clean base for custom themes. It applies simple borders and default fonts. ```r theme_vanilla(x) ``` -------------------------------- ### Highlight Rows Based on Condition Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/formatting-styles.md Use the highlight() function to set a background color for text in specific rows. This example highlights rows where the 'mpg' column is less than 20. ```r ft <- flextable(head(mtcars)) # Highlight rows where mpg < 20 ft <- highlight(ft, i = ~ mpg < 20, color = "yellow") ``` -------------------------------- ### regulartable() Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/core-constructors.md Creates a simple flextable with automatic, regular formatting applied to the data. ```APIDOC ## regulartable() ### Description Create a simple table with automatic formatting ### Signature ```r regulartable(data, col_keys = names(data)) ``` ### Parameters #### Parameters - **data** (data.frame) - Required - A data frame to display - **col_keys** (character) - Optional - Column names/keys to display. Default: `names(data)` ### Return Value A `flextable` object with simplified, regular formatting applied. ### Source `R/flextable.R` ``` -------------------------------- ### Adjust Table Autofit Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/README.md Demonstrates how to automatically adjust column widths of a flextable to fit its content using `autofit()`. An additional width can be specified. ```r # Adjust sizing ft <- autofit(ft, add_w = 0.1) ``` -------------------------------- ### Quantile-Based Cell Background Coloring Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/formatting-styles.md Apply conditional background colors to cells based on column values using a color function with bg(). This example colors the 'disp' column based on quantiles, ranging from 'wheat' to 'red'. ```r ft <- bg(ft, j = "disp", bg = scales::col_quantile(palette = c("wheat", "red"), domain = NULL) ) ``` -------------------------------- ### Applying Strikethrough Formatting Source: https://github.com/davidgohel/flextable/blob/main/NEWS.md Use `fp_text_default()` to configure default text formatting, including strikethrough, and then apply it using `as_strike()` to text chunks within a flextable. ```R library(flextable) # Configure default text properties with strikethrough default_text <- fp_text_default(strikethrough = TRUE) # Apply strikethrough to a flextable my_flextable <- as_strike(my_flextable, text = default_text) ``` -------------------------------- ### Formatting Logical Columns Source: https://github.com/davidgohel/flextable/blob/main/NEWS.md Ensures `format_fun.default` correctly handles logical columns for consistent formatting. ```r format_fun.default ``` -------------------------------- ### Set Global Flextable Defaults Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/configuration.md Use `set_flextable_defaults()` to define global formatting properties for all subsequent flextables. This is useful for enforcing corporate style guides or maintaining consistent table appearance. Properties set here are applied before any theme function. ```r set_flextable_defaults( font.family = "Calibri", font.size = 11, theme_fun = theme_booktabs, padding = 5, text.align = "left" ) # Now all new flextables use these defaults ft1 <- flextable(head(iris)) ft2 <- flextable(head(mtcars)) # Both use Calibri 11pt with booktabs theme # Reset to factory defaults init_flextable_defaults() ``` -------------------------------- ### Data Exploration Default Configuration Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/configuration.md Sets flextable defaults optimized for data exploration, using a monospaced font, smaller size, zebra theme, and minimal padding. ```r set_flextable_defaults( font.family = "Courier New", font.size = 9, theme_fun = theme_zebra, padding = 2 ) ``` -------------------------------- ### Creating a Compact Data Frame Summary Source: https://github.com/davidgohel/flextable/blob/main/NEWS.md Use `compact_summary()` to create a compact summary of a data.frame. This summary can then be transformed into a flextable using `as_flextable()`. ```R library(flextable) # Create a compact summary of a data frame summary_df <- compact_summary(iris) # Convert the summary to a flextable as_flextable(summary_df) ``` -------------------------------- ### Select Columns by Index Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/README.md Shows how to select columns using their numerical index, including single columns and ranges. This is useful when column names are not readily available or for positional operations. ```r # Select by index bold(ft, j = 1) # First column bold(ft, j = 2:4) # Columns 2-4 ``` -------------------------------- ### as_image() Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/content-composition.md Creates an image chunk for inserting images into table cells, supporting various formats and dimensions. ```APIDOC ## as_image() ### Description Create an image chunk ### Signature ```r as_image(src, width = 0.5, height = 0.5, unit = "in") ``` ### Parameters #### Parameters - **src** (character) - Required - Path to image file (PNG, JPG, GIF) - **width** (numeric) - Optional - Image width. Defaults to `0.5`. - **height** (numeric) - Optional - Image height. Defaults to `0.5`. - **unit** (character) - Optional - Unit: `"in"`, `"cm"`, `"mm"`. Defaults to `"in"`. ### Return Value A `chunk` object containing an image. ### Details Inserts an image into a table cell. Images are embedded and can be used in all output formats (Word, PowerPoint, HTML, PDF). ### Examples ```r ft <- flextable(head(iris)) # Create a sample image png_file <- file.path(tempdir(), "image.png") # (assumes image file exists) ft <- compose(ft, j = 1, i = 1, value = as_paragraph(as_image(png_file, width = 0.5, height = 0.5)) ) ``` ``` -------------------------------- ### Core Constructors Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/README.md Functions for creating and initializing flextable objects, as well as preparing data for specific table types. ```APIDOC ## Core Constructors ### `flextable()` **Description**: Create flextable from data frame. ### `empty()` **Description**: Clear column content. ### `as_flextable()` **Description**: Generic converter from various objects. ### `as_grouped_data()` **Description**: Create grouped data structure. ### `summarizor()` **Description**: Prepare descriptive statistics. ### `proc_freq()` **Description**: Create frequency tables. ### `compact_summary()` **Description**: Dataset summary. ### `clintables()` **Description**: Shift tables for clinical data. ``` -------------------------------- ### as_flextable() Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/core-constructors.md Converts various R objects into the flextable format, providing a flexible way to display different data types as tables. ```APIDOC ## as_flextable() ### Description Convert objects to flextable format ### Signature ```r as_flextable(x, ...) ``` ### Parameters #### Parameters - **x** (Various) - Required - Object to convert (data.frame, model, table, crosstab, etc.) - **...** (Various) - Optional - Additional arguments passed to specific methods ### Return Value A `flextable` object. ### Details `as_flextable()` is a generic function with methods for many R object types: - `as_flextable.data.frame()` — converts data frames - `as_flextable.grouped_data()` — converts grouped data with group labels - `as_flextable.tabular()` — converts tables::tabular objects - `as_flextable.gam()` — converts gam models - `as_flextable.htest()` — converts hypothesis tests - `as_flextable.lm()` — converts linear models - `as_flextable.glm()` — converts generalized linear models - `as_flextable.merMod()` — converts mixed models (lme4) - `as_flextable.lme()` — converts nlme models - `as_flextable.kmeans()` — converts kmeans results - `as_flextable.pam()` — converts PAM clustering results - `as_flextable.rtables()` — converts rtables objects - `as_flextable.tabulator()` — converts tabulator pivot tables ### Examples ```r # From a model fit <- lm(Sepal.Length ~ Sepal.Width, data = iris) ft <- as_flextable(fit) # From a crosstab ct <- table(iris$Species, iris$Sepal.Length > 6) ft <- as_flextable(ct) ``` ``` -------------------------------- ### as_sup() Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/content-composition.md Creates a superscript text chunk, useful for elements like footnote markers or exponents. It takes a value and an optional formatter function, along with additional arguments for the formatter. ```APIDOC ## as_sup() ### Description Create a superscript chunk. ### Signature ```r as_sup(x, formatter = format_fun, ...) ``` ### Parameters #### Arguments - **x** (Any) - Required - Value to format - **formatter** (function) - Optional - Function to convert x to character. Defaults to `format_fun`. - **...** (Various) - Optional - Additional arguments for formatter. ### Return Value A `chunk` object with superscript vertical alignment. ### Details Creates superscript text (raised above the baseline). Useful for footnote markers, exponents, etc. ### Examples ```r ft <- flextable(head(iris)) ft <- compose(ft, j = "Sepal.Length", value = as_paragraph( "Sepal.Length", as_sup("*") ) ) ``` ``` -------------------------------- ### Default Flextable Configuration Structure Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/types.md This structure outlines the global default formatting properties that apply to all newly created flextables. Use `get_flextable_defaults()` to retrieve current settings, `set_flextable_defaults(...)` to modify them, and `init_flextable_defaults()` to reset to initial values. ```r list( font.family = character, font.size = numeric, theme_fun = function, # Default theme padding = list( # Default padding top = numeric, bottom = numeric, left = numeric, right = numeric ), border.color = character, ... ) ``` -------------------------------- ### theme_booktabs() Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/sizing-and-themes.md Applies the booktabs theme to a flextable, offering publication-quality styling inspired by the LaTeX booktabs package. ```APIDOC ## theme_booktabs() ### Description Applies booktabs theme (publication quality) to a flextable object. ### Signature ```r theme_booktabs(x) ``` ### Parameters #### Path Parameters - **x** (flextable) - A flextable object ### Return Value The modified flextable object with booktabs theme applied. ### Details Applies professional styling inspired by the LaTeX booktabs package: clean lines, sans-serif fonts, appropriate spacing. Default theme applied to new flextables. ``` -------------------------------- ### Format flextable with highlighting and background colors Source: https://github.com/davidgohel/flextable/blob/main/README.md Illustrates applying conditional formatting to a flextable, including highlighting cells based on a condition and applying a color gradient to columns. ```r flextable(head(mtcars)) |> highlight(i = ~ mpg < 22, j = "disp", color = "#ffe842") |> bg( j = c("hp", "drat", "wt"), bg = scales::col_quantile(palette = c("wheat", "red"), domain = NULL) ) |> add_footer_lines("The 'mtcars' dataset") ``` -------------------------------- ### Tab Settings with j Argument Source: https://github.com/davidgohel/flextable/blob/main/NEWS.md Ensures `tab_settings()` correctly utilizes the `j` argument as expected. ```r tab_settings() ``` -------------------------------- ### Select Specific Parts of a Flextable Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/README.md Shows how to target specific parts of a flextable, such as the 'header', 'body', or 'footer', for formatting operations. 'all' selects all parts. ```r # Single part bold(ft, part = "header") bold(ft, part = "body") bold(ft, part = "footer") # All parts bold(ft, part = "all") ``` -------------------------------- ### Presentation/Slides Default Configuration Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/configuration.md Configures flextable defaults for presentations or slides, focusing on font, size, theme, and generous padding. ```r set_flextable_defaults( font.family = "Arial", font.size = 12, theme_fun = theme_vader, padding = 8 ) ``` -------------------------------- ### Select All Columns Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/README.md Illustrates how to select all columns in a flextable by setting the column selector `j` to `NULL`. This applies an operation to every column. ```r # Select all bold(ft, j = NULL) # All columns ``` -------------------------------- ### theme_vader() Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/sizing-and-themes.md Applies the vader theme, characterized by a dark background, white text, and prominent borders, suitable for presentations. ```APIDOC ## theme_vader() ### Description Applies the vader theme (dark background) to a flextable object. ### Signature ```r theme_vader(x) ``` ### Parameters #### Parameters - **x** (flextable) - A flextable object ### Return Value The modified `flextable` object with vader theme applied. ### Details Applies dark background with white text and prominent borders. High contrast theme suitable for presentations. ``` -------------------------------- ### clintables() Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/core-constructors.md Creates shift tables, which are useful for clinical reporting to visualize transitions between categorical states over time. ```APIDOC ## clintables() ### Description Create a shift table. ### Signature ```r clintables(data, vars, by = NULL, show_colnames = TRUE) ``` ### Parameters #### Parameters - **data** (data.frame) - Required - Input data (typically lab values) - **vars** (character) - Required - Variable columns to analyze - **by** (character) - Optional - Grouping variable(s) - **show_colnames** (logical) - Optional - Display column names ### Return Value A shift table data frame ready for flextable conversion. ### Details Creates "shift tables" commonly used in clinical reporting to show transitions between categorical states (e.g., normal/abnormal lab values at baseline and follow-up). ``` -------------------------------- ### theme_alafoli() Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/sizing-and-themes.md Applies the alafoli theme, offering lightweight styling for flextable objects. ```APIDOC ## theme_alafoli() ### Description Applies the alafoli theme (lightweight styling) to a flextable object. ### Signature ```r theme_alafoli(x) ``` ### Parameters #### Parameters - **x** (flextable) - A flextable object ### Return Value The modified `flextable` object with alafoli theme applied. ``` -------------------------------- ### Format various data types with format_fun() Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/advanced-utilities.md Use format_fun() to intelligently format different data types into character strings. It supports numeric, logical, Date, POSIXt, factor, and percentage types. For percentages, specify fmt = "pct". ```r format_fun(3.14159) # "3.14" format_fun(TRUE) # "TRUE" format_fun(as.Date("2024-01-15")) # "2024-01-15" format_fun(factor("A")) # "A" format_fun(0.5, fmt = "pct") # "50%" ``` -------------------------------- ### Select Rows by Formula Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/README.md Shows how to select rows based on a condition evaluated using a formula with the `~` operator. This allows for dynamic selection of rows based on data values. ```r # Select by formula bold(ft, i = ~ Sepal.Length > 5) # Rows where condition is TRUE ``` -------------------------------- ### Export and Output Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/README.md Functions for exporting flextables to various formats and rendering them for different environments. ```APIDOC ## Export and Output ### `as_html()` **Description**: Convert to HTML. ### `save_as_docx()` **Description**: Save as Word document. ### `save_as_pptx()` **Description**: Save as PowerPoint. ### `save_as_html()` **Description**: Save as HTML file. ### `to_wml()` **Description**: Convert to Word markup. ### `to_rtf()` **Description**: Convert to RTF. ### `to_latex()` **Description**: Convert to LaTeX. ### `to_typst()` **Description**: Convert to Typst. ### `as_image()` **Description**: Render as image (PNG/JPG/SVG). ### `as_grob()` **Description**: Render as grid graphics object. ### `for_patchwork()` **Description**: Wrap for patchwork. ### `body_add_flextable()` **Description**: Add to Word document. ### `ph_with_flextable()` **Description**: Add to PowerPoint slide. ### `split_rows()` **Description**: Split by rows for pagination. ### `split_columns()` **Description**: Split by columns for pagination. ### `knit_print()` **Description**: R Markdown/Quarto rendering. ``` -------------------------------- ### Apply Booktabs Theme to Flextable Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/sizing-and-themes.md Use theme_booktabs() for publication-quality tables inspired by LaTeX's booktabs package. It applies clean lines, sans-serif fonts, and appropriate spacing. ```r theme_booktabs(x) ``` -------------------------------- ### Sizing and Themes Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/README.md Functions for adjusting flextable dimensions, applying themes, and setting table properties. ```APIDOC ## Sizing and Themes ### `autofit()` **Description**: Auto-adjust dimensions. ### `width()` **Description**: Set column width. ### `height()` **Description**: Set row height. ### `flextable_sizes()` **Description**: Constrain width by shrinking. ### `set_table_properties()` **Description**: Set table layout. ### `theme_vanilla()` **Description**: Minimal theme. ### `theme_booktabs()` **Description**: Publication quality theme. ### `theme_box()` **Description**: Box/grid theme. ### `theme_zebra()` **Description**: Alternating row colors. ### `theme_vader()` **Description**: Dark theme. ### `theme_alafoli()` **Description**: Lightweight theme. ### `theme_tron()` **Description**: Technical theme. ### `theme_tron_legacy()` **Description**: Tron variant. ### `set_caption()` **Description**: Set table caption. ### `footnote()` **Description**: Add footnotes. ### `paginate()` **Description**: Control page breaks. ``` -------------------------------- ### as_equation() Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/advanced-utilities.md Inserts mathematical equations or formulas into cells, rendered as images in output documents. ```APIDOC ## as_equation() ### Description Inserts mathematical equations/formulas into cells. Rendered as images in output documents. ### Signature ```r as_equation(formula, height = 0.5, width = 1) ``` ### Parameters #### Parameters - **formula** (character) - Required - Mathematical formula text - **height** (numeric) - Optional - Equation height in inches (default: 0.5) - **width** (numeric) - Optional - Equation width in inches (default: 1) ### Return Value A chunk object containing the equation. ``` -------------------------------- ### minibar() Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/advanced-utilities.md Creates mini bar charts within cells for inline data visualization. ```APIDOC ## minibar() ### Description Creates inline bar charts for data visualization within cells. ### Signature ```r minibar(x, barcol = "blue", textcol = "black", height = 0.2, width = 1) ``` ### Parameters #### Parameters - **x** (numeric) - Required - Values to display as bars (0-1 or percentage) - **barcol** (character) - Optional - Bar color (default: "blue") - **textcol** (character) - Optional - Text color (default: "black") - **height** (numeric) - Optional - Bar height in inches (default: 0.2) - **width** (numeric) - Optional - Bar width in inches (default: 1) ### Return Value A chunk object with a mini bar chart. ### Examples ```r df <- data.frame( name = c("A", "B", "C"), value = c(0.3, 0.7, 0.5) ) ft <- flextable(df) ft <- compose(ft, j = "value", value = as_paragraph( minibar(value, barcol = "green", height = 0.1) ), use_dot = TRUE ) ``` ``` -------------------------------- ### style() Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/formatting-styles.md Sets multiple formatting properties (text, paragraph, cell) for specified cells in a flextable object. ```APIDOC ## style() ### Description Set multiple formatting properties at once. ### Signature ```r style( x, i = NULL, j = NULL, pr_t = NULL, pr_p = NULL, pr_c = NULL, part = "body" ) ``` ### Parameters #### Arguments - **x** (`flextable`) - A flextable object - **i** (`integer|formula`) - Optional - Row selector - **j** (`integer|character`) - Optional - Column selector - **pr_t** (`fp_text|fp_text_lite`) - Optional - Text formatting properties (font, size, color, bold, italic) - **pr_p** (`fp_par|fp_par_lite`) - Optional - Paragraph properties (alignment, padding, line spacing) - **pr_c** (`fp_cell`) - Optional - Cell properties (background, borders, vertical alignment) - **part** (`character`) - Optional - Table part: "all", "header", "body", "footer". Defaults to "body". ### Return Value The modified `flextable` object. ### Examples ```r library(officer) ft <- flextable(head(mtcars)) # Define formatting cell_border <- fp_cell(border = fp_border(color = "black")) par_center <- fp_par(text.align = "center") text_red <- fp_text(color = "red", bold = TRUE) # Apply to selection ft <- style(ft, i = 1:2, j = 1:3, pr_t = text_red, pr_p = par_center, pr_c = cell_border, part = "header" ) ``` ``` -------------------------------- ### tabulator() Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/advanced-utilities.md Creates pivot-style summary tables (cross-tabulations) from a data frame. It allows for flexible grouping of rows and columns, aggregation of a specified value column using a given function, and inclusion of margin totals. ```APIDOC ## tabulator() ### Description Creates pivot-style summary tables (cross-tabulations) from a data frame. It allows for flexible grouping of rows and columns, aggregation of a specified value column using a given function, and inclusion of margin totals. ### Signature ```r tabulator( data, rows = NULL, cols = NULL, value = NULL, fun = sum, margins = TRUE ) ``` ### Parameters #### Data - **data** (`data.frame`) - Required - Input data frame. #### Grouping - **rows** (`character` or `NULL`) - Optional - Column(s) to use for row grouping. Defaults to `NULL`. - **cols** (`character` or `NULL`) - Optional - Column(s) to use for column grouping. Defaults to `NULL`. #### Value and Aggregation - **value** (`character` or `NULL`) - Optional - The column containing values to aggregate. Defaults to `NULL`. - **fun** (`function`) - Optional - The aggregation function to apply to the `value` column. Defaults to `sum`. #### Margins - **margins** (`logical`) - Optional - Whether to include margin totals (row and column totals). Defaults to `TRUE`. ### Return Value A `tabulator` object, which can be further processed and converted into a flextable using `as_flextable()`. ### Details This function is designed for creating pivot/cross-tabulation tables. It automatically computes group totals and grand totals when `margins` is set to `TRUE`. ### Examples ```r # Example of creating a pivot table my_data <- mtcars tab <- tabulator(data = my_data, rows = "cyl", cols = "gear", value = "mpg", fun = mean) # Convert the tabulator object to a flextable ft <- as_flextable(tab) print(ft) ``` ``` -------------------------------- ### as_b() Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/content-composition.md Creates a bold text chunk for use within flextable cells. It takes a value and an optional formatter function to convert it to character, along with additional arguments for the formatter. ```APIDOC ## as_b() ### Description Create a bold text chunk. ### Signature ```r as_b(x, formatter = format_fun, ...) ``` ### Parameters #### Arguments - **x** (Any) - Required - Value to format - **formatter** (function) - Optional - Function to convert x to character. Defaults to `format_fun`. - **...** (Various) - Optional - Additional arguments for formatter. ### Return Value A `chunk` object with bold formatting applied. ### Examples ```r ft <- flextable(head(iris)) ft <- compose(ft, j = "Sepal.Length", value = as_paragraph("Value: ", as_b(Sepal.Length)) ) ``` ``` -------------------------------- ### theme_tron() Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/sizing-and-themes.md Applies the tron theme, providing a technical styling with accent colors and distinctive design elements. ```APIDOC ## theme_tron() ### Description Applies the tron theme (technical styling) to a flextable object. ### Signature ```r theme_tron(x) ``` ### Parameters #### Parameters - **x** (flextable) - A flextable object ### Return Value The modified `flextable` object with tron theme applied. ### Details Applies a technical theme with accent colors and distinctive styling. ``` -------------------------------- ### Previewing Table Data with str() Source: https://github.com/davidgohel/flextable/blob/main/NEWS.md Uses `str()` in `print.flextable(preview = "log")` to display initial data values, improving compatibility with objects like ggplot2 v4. ```r print.flextable(preview = "log") ``` -------------------------------- ### Add Header and Footer Lines Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/README.md Shows how to add descriptive lines to the header and footer of a flextable using `add_header_lines()` and `add_footer_lines()`. This is useful for titles and source information. ```r # Manage structure ft <- add_header_lines(ft, "Table 1: Iris Data") ft <- add_footer_lines(ft, "Source: R datasets") ``` -------------------------------- ### as_image() Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/export-and-output.md Renders a flextable object as an image in PNG, JPG, or SVG format. This function is useful for exporting tables as standalone image files or for embedding them in reports where direct flextable rendering is not supported. It requires the webshot2 package for HTML-based rendering. ```APIDOC ## as_image() ### Description Render flextable as image ### Signature ```r as_image( x, width = 7, height = NULL, res = 96, format = "png" ) ``` ### Parameters | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | `x` | `flextable` | — | A flextable object | | `width` | `numeric` | `7` | Image width in inches | | `height` | `numeric` | `NULL` | Image height (auto-calculated if NULL) | | `res` | `numeric` | `96` | Resolution in dpi | | `format` | `character` | `"png"` | Image format: `"png"`, `"jpg"`, `"svg"` | ### Return Value An image object (raster for PNG/JPG, SVG string for SVG). ### Details Renders the flextable as a raster image (PNG/JPG) or vector graphics (SVG). Requires external dependencies (webshot2 for HTML-based rendering). ### Examples ```r ft <- flextable(head(iris)) # Render as PNG img <- as_image(ft, width = 6, format = "png") # Render as SVG (vector graphics) svg <- as_image(ft, width = 6, format = "svg") ``` ``` -------------------------------- ### flextable() Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/api-reference/core-constructors.md Creates a flextable object from a data frame. It allows customization of displayed columns, cell dimensions, and uses labels if available. ```APIDOC ## flextable() ### Description Create a flextable from a data frame. ### Signature ```r flextable( data, col_keys = names(data), cwidth = 0.75, cheight = 0.25, defaults = list(), theme_fun = theme_booktabs, use_labels = TRUE ) ``` ### Parameters #### Data - `data` (data.frame) - Required - A data frame to display #### Column Keys - `col_keys` (character) - Optional - Column names/keys to display. If some column names are not in the dataset, they will be added as blank columns. Defaults to `names(data)`. #### Cell Dimensions - `cwidth` (numeric) - Optional - Initial width for cells in inches. Defaults to `0.75`. - `cheight` (numeric) - Optional - Initial height for cells in inches. Defaults to `0.25`. #### Deprecated Parameters - `defaults` (list) - Deprecated — use `set_flextable_defaults()` instead. Defaults to `list()`. - `theme_fun` (function) - Deprecated — use `set_flextable_defaults()` instead. Defaults to `theme_booktabs`. #### Labels - `use_labels` (logical) - Optional - If TRUE, any column labels or value labels present in the dataset will be used for display purposes. Defaults to `TRUE`. ### Return Value A `flextable` object with three parts: `header`, `body`, and `footer`. ### Details The returned flextable has a basic structure with one header row containing column names and body rows matching the input data frame. All column keys must be unique or an error is raised. If `data` is a data.table, tibble, or other data frame subclass, it is converted to a base data.frame. New lines expressed as `\n` are converted to soft returns. Tabs expressed as `\t` are handled differently per output format. ### Examples ```r # Basic usage ft <- flextable(head(mtcars)) # Specify custom column order ft <- flextable(mtcars, col_keys = c("cyl", "mpg", "disp")) # Add blank columns ft <- flextable(mtcars, col_keys = c("cyl", "mpg", "disp", "notes")) ``` ``` -------------------------------- ### Set Flextable Defaults and Generate Officer Document Source: https://github.com/davidgohel/flextable/blob/main/_autodocs/configuration.md Sets global flextable defaults for font size, theme, and padding. Then, it creates an R Markdown document using the officer package, adding paragraphs and flextables that inherit these defaults. Finally, it prints the document to a Word file. ```r library(flextable) library(officer) # Set defaults set_flextable_defaults( font.size = 11, theme_fun = theme_booktabs, padding = 5 ) # Create document with consistent tables doc <- read_docx() | body_add_paragraph("Table 1: Summary") | body_add_flextable(flextable(head(iris))) | body_add_paragraph("Table 2: Cars") | body_add_flextable(flextable(head(mtcars))) print(doc, target = "report.docx") ```