knitr::opts_chunk$set( collapse = TRUE, comment = "#>", fig.path = "README-" ) devtools::load_all()
pformat provides powerful string interpolation and formatting capabilities. It is a R language implementation of Python's new style string formatting API, coupled with some original features.
integer
, double
, complex
), date (Date
,
IDate
, POSIXt
) and character
types out-of-the-box.pformat()
only
the format string, and it will look for corresponding data on the environment.A pair of braces and everything inside them form a placeholder. The simplest use case is that of positional formatting: arguments are assigned to placeholders according to their position.
pformat("{} {}", "one", "two")
You can give placeholders an explicit positional index. This allows for re-arranging the order of display without changing the arguments. Note: contrary to Python, in pformat indices start from 1 and not from 0.
pformat("{2} {1}", "one", "two")
pformat is vectorized, so you can generate many formatted strings using a single call
pformat("Name: {}; Age: {}", c("Abby", "Bob", "Carl"), 22:24)
Usual recycling rules apply:
pformat("{}-{}{}", "expr", c("a", "b", "c"), 1:2)
pformat provides three ways of using named placeholders:
%>%
provided by the magrittr
package.That's also the order which pformat uses when looking for corresponding names. The following example illustrates the three methods, where all calls produce same output.
# keyword arguments pformat("Name: {name}; Age: {age}", name = c("Abby", "Bob", "Carl"), age = 22:24) # passing a data frame as the first parameter people = data.frame(name = c("Abby", "Bob", "Carl"), age = 22:24) pformat(people, "Name: {name}; Age: {age}") # the same as above but using pipe library(magrittr) people %>% pformat("Name: {name}; Age: {age}") # evaluation on the environment name = c("Abby", "Bob", "Carl") age = 22:24 pformat("Name: {name}; Age: {age}")
Placeholders can hold not only identifiers but any R expression, provided that its result type is supported by pformat.
n = 9 pformat("{n} x {i} = {n * i}", i = 1:10)
df = data.frame(name = c("Walter", "Frederick", "Lindsey"), surname = c("Unzueta", "Winstead", "Chambers")) df %>% pformat("{substr(name, 1, 1)}. {surname}")
pformat uses (will use) the same format string syntax as Python. See Python docs. Development in progress.
Date formatting uses the traditional strftime()
conversion specification, just
like Python. See strftime
's help page for more details.
pformat("Mother's day: {:%d/%m/%Y}", as.Date("2016-05-08"))
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.