In python there's a nice function (str .format
) that can really easily replace variables (encoded like {variable}
) in a string with values stored in a dict (with values named by variable name). Like so:
vars=dict(animal="shark", verb="ate", noun="fish") string="Sammy the {animal} {verb} a {noun}." print(string.format(**vars))
Sammy the shark ate a fish.
What is the simplest solution in R
? Is there a built-in equivalent 2-argument function that takes a string with variables encoded in the same way and replaces them with named values from a named list
?
If there is no built-in function in R, is there one in a published package?
If there is none in a published package, what would you use to write one?
The rules: the string is given to you with variables encoded like "{variable}". The variables must be encoded as a list
. I will answer with my custom-made version, but will accept an answer that does it better than I did.
format() formatting operations; it only works in old-style % string formatting. It indeed converts the object to a representation through the repr() function. In str. format() , ! r is the equivalent, but this also means that you can now use all the format codes for a string.
Use time. strptime to parse from string to time struct. If the string doesn't match the format it raises ValueError .
They are used for formatting strings. %s acts a placeholder for a string while %d acts as a placeholder for a number.
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ł
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With