
Last chance! 50% off unlimited learning
Sale ends in
template.replace
replaces keys within special markups with
values in a so-called template file. Pieces of R code can be put into
the markups of the template file, and are evaluated during the
replacement.
template.replace(text, replacement, eval = FALSE,
key.pattern = NULL, code.pattern = NULL)
vector of character strings, the template text.
the list values to replace in text
.
boolean, TRUE
if the code within
code.pattern
has to be evaluated, FALSE
otherwise.
custom pattern for key replacement (see below)
custom pattern for code replacement (see below)
Gilles Pujol
In most cases, a computational code reads its inputs from a text file. A template file is like an input file, but where some missing values, identified with generic keys, will be replaced by specific values.
By default, the keys are enclosed into markups of the form $(KEY)
.
Code to be interpreted with R can be put in the template text. Pieces
of code must be enclosed into markups of the form
@{CODE}
. This is useful for example for formating the key
values (see example). For interpreting the code, set eval = TRUE
.
Users can define custom patterns. These patterns must be
perl-compatible regular expressions (see regexpr
.
The default ones are:
key.pattern = "\\$\\(KEY\\)"
code.pattern = "@\\{CODE\\}"
Note that special characters have to be escaped both (one for perl, one for R).
txt <- c("Hello $(name)!", "$(a) + $(b) = @{$(a)+$(b)}",
"pi = @{format(pi,digits=5)}")
replacement <- list(name = "world", a = 1, b = 2)
# 1. without code evaluation:
txt.rpl1 <- template.replace(txt, replacement)
print(txt.rpl1)
# 2. with code evalutation:
txt.rpl2 <- template.replace(txt, replacement, eval = TRUE)
print(txt.rpl2)
Run the code above in your browser using DataLab