Perform highly targeted text replacement with a regex pattern
Source:R/text_transform.R
text_replace.Rd
The text_replace()
function provides a specialized interface for replacing
text fragments in table cells with literal text. You need to ensure that
you're targeting the appropriate cells with the locations
argument. Once
that is done, the remaining two values to supply are for the regex pattern
(pattern
) and the replacement for all matched text (replacement
).
Usage
text_replace(data, pattern, replacement, 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.- pattern
Regex pattern to match with
scalar<character>
--- requiredA regex pattern used to target text fragments in the cells resolved in locations.
- replacement
Replacement text
scalar<character>
--- requiredThe replacement text for any matched text fragments.
- locations
Locations to target
<locations expressions>
--- default:cells_body()
The cell or set of cells to be associated with the text transformation. Only the
cells_body()
,cells_stub()
,cells_row_groups()
,cells_column_labels()
, andcells_column_spanners()
helper functions 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 the metro
dataset to create a gt table. With the cols_merge()
function, we'll merge the name
and caption
columns together but only if
caption
doesn't have an NA
value (the special pattern
syntax of "{1}<< ({2})>>"
takes care of this). This merged content is now part of the name
column. We'd like to modify this further wherever there is text in
parentheses: (1) make that text italicized, and (2) introduce a line break
before the text in parentheses. We can do this with the text_replace()
function. The pattern
value of "\\((.*?)\\)"
will match on text between
parentheses, and the inner "(.*?)"
is a capture group. The replacement
value of "<br>(<em>\\1</em>)"
puts the capture group text "\\1"
within
<em>
tags, wraps literal parentheses around it, and prepends a line break
tag.
metro |>
dplyr::select(name, caption, lines) |>
dplyr::slice(110:120) |>
gt() |>
cols_merge(
columns = c(name, caption),
pattern = "{1}<< ({2})>>"
) |>
text_replace(
locations = cells_body(columns = name),
pattern = "\\((.*?)\\)",
replacement = "<br>(<em>\\1</em>)"
)
See also
Other text transforming functions:
text_case_match()
,
text_case_when()
,
text_transform()