View source: R/text_transform.R
text_replace | R Documentation |
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
).
text_replace(data, pattern, replacement, locations = cells_body())
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 |
An object of class gt_tbl
.
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>)" )
4-1
v0.9.0
(Mar 31, 2023)
Other text transforming functions:
text_case_match()
,
text_case_when()
,
text_transform()
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.