Populate string templates containing keys with their values. The keys are interpreted as regular expressions. Results can optionally be evaluated as R expressions.

absorb(
    key, 
    value, 
    text, 
    sep = "_",
    trace = FALSE,
    evaluate = FALSE
)

Arguments

key

A vector that can be coerced to type character.

value

A vector with the same length as key.

text

A (optionally named) character vector containing patterns.

sep

Delimiter to separate values by in the placeholder for duplicate patterns. Defaults to "_"

trace

Should the recursion results be printed to the console each iteration? Defaults to FALSE.

evaluate

Should the result(s) be evaluated as R expressions? Defaults to FALSE.

Details

The inputs are iterated in sequential order to replace each pattern with its corresponding value. It is possible that a subsequent pattern could match with a prior result, and hence be replaced more than once. If duplicate keys exist, the placeholder will be filled with a collapsed string of all the values for that key.

Value

  • If evaluate = FALSE (default), a character vector the same length as text with all matching patterns replaced by their value.

  • Otherwise, a list with the same length as text.

Author

Alex Zajichek

Examples

#Simple example
absorb(
    key = c("mean", "sd", "var"),
    value = c("10", "2", "4"),
    text = 
        c("MEAN: mean, SD: sd",
          "VAR: var = sd^2",
          MEAN = "mean"
        )
)
#>                                                  MEAN 
#> "MEAN: 10, SD: 2"    "VAR: 4 = 2^2"              "10" 

#Evaluating results
absorb(
    key = c("mean", "mean", "sd", "var"),
    value = c("10", "20", "2", "4"),
    text = c("(mean)/2", "sd^2"),
    sep = "+",
    trace = TRUE,
    evaluate = TRUE
) %>%
    rlang::flatten_dbl()
#> (mean)/2 sd^2 
#> (10+20)/2 sd^2 
#> (10+20)/2 2^2 
#> [1] 15  4