text_replace {gt} | R Documentation |
Perform highly targeted text replacement with a regex pattern
Description
text_replace()
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 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
This is the gt table object that is commonly created through use of the
|
pattern |
Regex pattern to match with
A regex pattern used to target text fragments in the cells resolved in locations. |
replacement |
Replacement text
The replacement text for any matched text fragments. |
locations |
Locations to target
The cell or set of cells to be associated with the text transformation.
Only |
Value
An object of class gt_tbl
.
Examples
Use the metro
dataset to create a gt table. With cols_merge()
,
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 text_replace()
. 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>)" )

Function ID
4-1
Function Introduced
v0.9.0
(Mar 31, 2023)
See Also
Other text transforming functions:
text_case_match()
,
text_case_when()
,
text_transform()