sprintf format strings: reference by name?

1. Try gsubfn in the gsubfn package:

library(gsubfn)
parameters <- list(label = "months", april = 4, may = 5, june = 6)

gsubfn("\\w+", parameters, "label: april, may, june")

2. or try fn$ from the same package:

with(parameters, fn$identity("$label: $april, $may, $june"))

3. Here is a short infix function that transforms a format string and a list of parameters to a sprintf and then runs it:

library(gsubfn)
`%format%` <- function(fmt, list) {
    pat <- "%\\(([^)]*)\\)"
    fmt2 <- gsub(pat, "%", fmt)
    list2 <- list[strapplyc(fmt, pat)[[1]]]
    do.call("sprintf", c(fmt2, list2))
}

Use it like this:

> '%(label)s: %(april)d %(may)d %(june)d' %format% parameters
[1] "months: 4 5 6"

Although this is not built in to the system sprintf functions that R is using (see man printf for the system docs), it's easy enough to implement such a feature in R by replacing the named references with their respective positions -

sprintf_named <- function(fmt, ...) {
  args <- list(...)
  argn <- names(args)
  if(is.null(argn)) return(sprintf(fmt, ...))

  for(i in seq_along(args)) {
    if(argn[i] == "") next;
    fmt <- gsub(sprintf("%%{%s}", argn[i]), sprintf("%%%d$", i), fmt, fixed = TRUE)
  }

  do.call(sprintf, append(args, fmt, 0))
}

Here is an example usage:

sprintf_named("%{HIA}s!! %{RYLAH}s", RYLAH="Rock You Like a Hurricane", HIA="Here I Am")
## [1] "Here I Am!! Rock You Like a Hurricane"

We could also make it an infix:

`%format%` <- function(left, right) do.call(sprintf_named, append(right, left, 0))

"%{b}s %{a}s" %format% list(a='ya', b='boo')
## [1] "boo ya"

Tags:

R