vadr (version 0.01)

interpolate: Evaluate expressions within strings.

Description

Interpolate evaluated expressions into strings.

Usage

interpolate(str, begin = ".(", end = ")", envir = arg_env(str, environment()))
interply(str, begin = ".(", end = ")", envir = arg_env(str, environment()))
str %#% args

Arguments

str
A template string. For interply, must have length 1.
begin
The beginning delimiter.
end
The ending delimiter.
envir
The environment evaluation takes place in. Defaults to the lexical environment of the template.
args
A list or named vector; interpolation happens in an environment with these values bound.

Value

A character vector.

Details

For interpolate, the argument is scanned for substrings that look like ".(expr)". These are replaced by the evaluation of the expression. Expressions will be matched respecting the balancing of braces and quotes.

interply generates a function that performs this interpolation for a particular string. The interpolation is repeated along the arguments applied to the function (so the usage is interply(".(x),.(y)")(x=val, y=val), similar to mply and qqply.) Note unnamed arguments can be referred to as ..1, ..2, etc.

%#% is a shortcut for applying interpolation to data from a list or named vector. string %#% values is equivalent to interply(string) %()% values.

See Also

qq qqply mply

Examples

Run this code
foo<-1; bar<-"two"; baz <- "III"
interpolate(c(".(foo),", "a .(bar)", "a .(foo) .(bar) .(baz)"))
interply("hello .(..1)")(c("world", "nurse", "kitty"))
interply("hello {{q}}", begin="{{", end="}}")(q=c("there", "you"))
"hello .(x)" %#% c(x="world")

#shell-style interpolation -- "$" start and no end delim
interply("$hello, ${paste(rep('hello', 3), collapse=' ')}, $'hi'",
         begin="$", end=""
         )(hello="hola")

# Compliant 99 Bottles implementation:
bottles <- interply(
  ".(ifelse(n%%100>0, n%%100, 'no more')) bottle.('s'[n%%100!=1]) of beer")
initcap <- function(x) {substr(x, 1, 1) <- toupper(substr(x, 1, 1)); x}
verse <- interply(
  paste0(".(initcap(bottles(n=n))) on the wall, .(bottles(n=n)).\n",
         ".(c('Go to the store and buy some more,',",
         "    'Take one down and pass it around,')[(n%%100!=0)+1])",
         " .(initcap(bottles(n=n-1))) on the wall."))
cat(verse(n=99:0), sep="\n\n")

Run the code above in your browser using DataCamp Workspace