Import the package. We will also make heavy usage of chaining: see magrittr’s documentation. We will use knitr’s kable to format tables.

library(sprintfr)
library(magrittr)
library(knitr)

Base Components

Let’s see what kind of componenets we can use in our string format.

string_base %>% kable
integer octal hex double scientific auto binary string percent
i o x f e g a s %

Each of these base time can be used in a string format:

string_format(double, " ", integer)
## [1] "%.f %.i"

Modifications

Each base component can be modified with flags or changing options. The default bases will always have no options or flags selected. Each option and flag has a corresponding function.

You can see options available.

string_option %>% kable
before_decimal after_decimal use_input
number of digits before the decimal place number of digits after the decimal place sprintf input argument number

Option assignment has two arguments, an object to modify and new value.

string_format(double %>% use_input(2))
## [1] "%2$.f"

You can also see flags available.

string_flag %>% kable
left_justify always_sign prefix_space zero_pad hex_prefix always_decimal remove_zeros
- + 0 # # #

Flag assignment has two arguments, an object to modify and new value. By default, the second argument is TRUE. Flags can be turned off by assigning a value of FALSE. For more information about flags, see the sprintf documentation.

string_format(double %>% zero_pad)
## [1] "%0.f"
string_format(double %>% zero_pad %>% zero_pad(FALSE))
## [1] "%.f"

Example

Let’s build a complicated string format for fun.

string_format(list(double %>% 
                     zero_pad,
                   "1%",
                   double %>% 
                     left_justify) %>%
                use_input(1) %>%
                always_sign %>%
                before_decimal(3) %>%
                after_decimal(0),
              sep = " and ")
## [1] "%1$+03.0f and 1%% and %1$-+3.0f"

sprintfr is clever about applying modifications over lists. This allows bulk modification. Raw strings can be modified (as “text” above), but it will not effect how they are displayed. Percentages in raw strings will automatically be doubled. Note that the sep argument will be used if named, and defaults to “”. This works the same way as in base paste.