Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

replace

r

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.

like image 998
nsheff Avatar asked Jun 26 '17 15:06

nsheff


People also ask

What is R format in Python?

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.

How do you check the format of a string in Python?

Use time. strptime to parse from string to time struct. If the string doesn't match the format it raises ValueError .

What are %s %d in Python?

They are used for formatting strings. %s acts a placeholder for a string while %d acts as a placeholder for a number.


1 Answers

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ł

like image 104
Pawel Stradowski Avatar answered Sep 21 '22 19:09

Pawel Stradowski