View source: R/text_transform.R
| text_case_when | R Documentation |
text_case_when() provides a useful interface for a case-by-case approach to
replacing entire table cells. First off, you have to make sure you're
targeting the appropriate cells with the .locations argument. Following
that, you supply a sequence of two-sided formulas matching of the general
form: <logical_stmt> ~ <new_text>. In the left hand side (LHS) there should
be a predicate statement that evaluates to a logical vector of length one
(i.e., either TRUE or FALSE). To refer to the values undergoing
transformation, you need to use the x variable.
text_case_when(.data, ..., .default = NULL, .locations = cells_body())
.data |
The gt table data object
This is the gt table object that is commonly created through use of the
|
... |
Matching expressions
A sequence of two-sided formulas. The left hand side (LHS)
determines which values match this case. The right hand side (RHS) provides
the replacement text (it must resolve to a value of the |
.default |
Default replacement text
The replacement text to use when cell values aren't matched by any of the
LHS inputs. If |
.locations |
Locations to target
The cell or set of cells to be associated with the text transformation.
Only |
An object of class gt_tbl.
Use a portion of the metro dataset to create a gt table. We'll use
text_case_when() to supply pairs of predicate statements and replacement
text. For the connect_rer column, we will perform a count of pattern
matches with stringr::str_count() and determine which cells have 1, 2, or 3
matched patterns. For each of these cases, descriptive replacement text is
provided. Here, we use a .default value to replace the non-matched
cases with an empty string (""). Finally, we use cols_label() to modify
the labels of the three columns.
metro |>
dplyr::slice_max(passengers, n = 10) |>
dplyr::select(name, lines, connect_rer) |>
gt() |>
text_case_when(
stringr::str_count(x, pattern = "[ABCDE]") == 1 ~ "One connection.",
stringr::str_count(x, pattern = "[ABCDE]") == 2 ~ "Two connections.",
stringr::str_count(x, pattern = "[ABCDE]") == 3 ~ "Three connections.",
.default = "", .locations = cells_body(columns = connect_rer)
) |>
cols_label(
name = "Station",
lines = "Lines Serviced",
connect_rer = "RER Connections"
)
4-2
v0.9.0 (Mar 31, 2023)
Other text transforming functions:
text_case_match(),
text_replace(),
text_transform()
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.