Is there an R equivalent of python's string `format` function? Is there an R equivalent of python's string `format` function? r r

Is there an R equivalent of python's string `format` function?


I found another solution: glue package from the tidyverse: https://github.com/tidyverse/glue

An example:

library(glue)animal <- "shark"verb <- "ate"noun <- "fish"string="Sammy the {animal} {verb} a {noun}."glue(string)Sammy the shark ate a fish.

If you insist on having list of variables, you can do:

l <- list(animal = "shark", verb = "ate", noun = "fish")do.call(glue, c(string , l))Sammy the shark ate a fish.

Regards

Paweł


Here's a function that converts the { and } to <%= and %> and then uses brew from the brew package (which you need to install):

form = function(s,...){ s = gsub("\\}", "%>", gsub("\\{","<%=",s)) e = as.environment(list(...)) parent.env(e)=.GlobalEnv brew(text=s, envir=e)}

Tests:

> form("Sammy the {animal} {verb} a {noun}.", animal = "shark", verb="made", noun="car")Sammy the shark made a car.> form("Sammy the {animal} {verb} a {noun}.", animal = "shark", verb="made", noun="truck")Sammy the shark made a truck.

It will fail if there's any { in the format string that don't mark variable substitutions, or if it has <%= or any of the other brew syntax markers in it.


Since it appears I cannot find a built-in or even a package with such a function, I tried to roll my own. My function relies on the stringi package. Here is what I have come up with:

strformat = function(str, vals) {    vars = stringi::stri_match_all(str, regex = "\\{.*?\\}", vectorize_all = FALSE)[[1]][,1]    x = str    for (i in seq_along(names(vals))) {        varName = names(vals)[i]        varCode = paste0("{", varName, "}")        x = stringi::stri_replace_all_fixed(x, varCode, vals[[varName]], vectorize_all = TRUE)    }    return(x)}

Example:

> str = "Sammy the {animal} {verb} a {noun}."> vals = list(animal="shark", verb="ate", noun="fish")> strformat(str, vals)[1] "Sammy the shark ate a fish."