knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.path = "README-"
)

devtools::load_all()

pformat

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.

Features

Examples

Basic usage

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")

Vectorization

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)

Named placeholders

pformat provides three ways of using named placeholders:

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}")

Expressions

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}")

Formatting

Integers, floating point numbers, and strings

pformat uses (will use) the same format string syntax as Python. See Python docs. Development in progress.

Dates

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"))


lurodrigo/pformat documentation built on May 21, 2019, 8:58 a.m.