gt_index: Return the underlying data, arranged by the internal index

View source: R/gt_index.R

gt_indexR Documentation

Return the underlying data, arranged by the internal index

Description

This is a utility function to extract the underlying data from a gt table. You can use it with a saved gt table, in the pipe (⁠%>%⁠) or even within most other gt functions (eg tab_style()). It defaults to returning the column indicated as a vector, so that you can work with the values. Typically this is used with logical statements to affect one column based on the values in that specified secondary column. Alternatively, you can extract the entire ordered data according to the internal index as a tibble. This allows for even more complex steps based on multiple indices.

Usage

gt_index(gt_object, column, as_vector = TRUE)

Arguments

gt_object

An existing gt table object

column

The column name that you intend to extract, accepts tidyeval semantics (ie mpg instead of "mpg")

as_vector

A logical indicating whether you'd like just the column indicated as a vector, or the entire dataframe

Value

A vector or a tibble

Figures

gt_index_style.png

Function ID

2-20

See Also

Other Utilities: add_text_img(), fa_icon_repeat(), fmt_pad_num(), fmt_pct_extra(), fmt_symbol_first(), generate_df(), gt_add_divider(), gt_badge(), gt_double_table(), gt_duplicate_column(), gt_fa_column(), gt_fa_rank_change(), gt_fa_rating(), gt_fa_repeats(), gt_highlight_cols(), gt_highlight_rows(), gt_img_border(), gt_img_circle(), gt_img_multi_rows(), gt_img_rows(), gt_merge_stack_color(), gt_merge_stack(), gt_two_column_layout(), gtsave_extra(), img_header(), pad_fn(), tab_style_by_grp()

Examples

library(gt)

# This is a key step, as gt will create the row groups
# based on first observation of the unique row items
# this sampling will return a row-group order for cyl of 6,4,8

set.seed(1234)
sliced_data <- mtcars %>%
  dplyr::group_by(cyl) %>%
  dplyr::slice_head(n = 3) %>%
  dplyr::ungroup() %>%
  # randomize the order
  dplyr::slice_sample(n = 9)

# not in "order" yet
sliced_data$cyl

# But unique order of 6,4,8
unique(sliced_data$cyl)

# creating a standalone basic table
test_tab <- sliced_data %>%
  gt(groupname_col = "cyl")

# can style a specific column based on the contents of another column
tab_out_styled <- test_tab %>%
  tab_style(
    locations = cells_body(mpg, rows = gt_index(., am) == 0),
    style = cell_fill("red")
  )

# OR can extract the underlying data in the "correct order"
# according to the internal gt structure, ie arranged by group
# by cylinder, 6,4,8
gt_index(test_tab, mpg, as_vector = FALSE)

# note that the order of the index data is
# not equivalent to the order of the input data
# however all the of the rows still match
sliced_data

gtExtras documentation built on Sept. 16, 2023, 1:08 a.m.