Perform whole text replacements using a 'case-when'-expression approach
Source:R/text_transform.R
text_case_when.Rd
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.
Usage
text_case_when(.data, ..., .default = NULL, .locations = cells_body())
Arguments
- .data
The gt table data object
obj:<gt_tbl>
// requiredThis is the gt table object that is commonly created through use of the
gt()
function.- ...
Matching expressions
<multiple expressions>
// requiredA 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
character
class). The LHS inputs must evaluate to logical vectors.- .default
Default replacement text
scalar<character>
// default:NULL
(optional
)The replacement text to use when cell values aren't matched by any of the LHS inputs. If
NULL
, the default, no replacement text will be used.- .locations
Locations to target
<locations expressions>
// default:cells_body()
The cell or set of cells to be associated with the text transformation. Only
cells_column_spanners()
,cells_column_labels()
,cells_row_groups()
,cells_stub()
, andcells_body()
can be used here. We can enclose several of these calls within alist()
if we wish to make the transformation happen at different locations.
Examples
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::arrange(desc(passengers)) |>
dplyr::select(name, lines, connect_rer) |>
dplyr::slice_head(n = 10) |>
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"
)
See also
Other text transforming functions:
text_case_match()
,
text_replace()
,
text_transform()