Title: | Dynamic String Formatting |
---|---|
Description: | Pass named and unnamed character vectors into specified positions in strings. This represents an attempt to replicate some of python's string formatting. |
Authors: | Alexander Hoyle |
Maintainer: | Alexander Hoyle <[email protected]> |
License: | MIT + file LICENSE |
Version: | 0.1.2 |
Built: | 2024-12-08 06:49:08 UTC |
Source: | CRAN |
%p%
and %s%
are wrappers for paste0(..., collapse = '')
and
paste(..., collapse = ' ')
, respectively, which combine two character vectors.
x %p% y x %s% y
x %p% y x %s% y
x , y
|
A character vector |
'the quick brown fox jum' %p% 'ped over the lazy dog' gen_sql <- function(column, table) "SELECT" %s% column %s% "FROM" %s% table
'the quick brown fox jum' %p% 'ped over the lazy dog' gen_sql <- function(column, table) "SELECT" %s% column %s% "FROM" %s% table
Pass variables into strings using pairs of curly brackets to identify points of insertion.
string %f% args
string %f% args
string |
A character vector |
args |
A (possibly named) atomic vector |
# order matters when not using a named vector 'the quick {} fox jumped {} the lazy {}' %f% c('brown', 'over', 'dog') # use a named vector to insert values by referencing them in the string gen_sql_query <- function(column, table, id){ query <- "SELECT {col} FROM {tab} WHERE pk = {id}" query %f% c(col = column, tab = table, id = id) } gen_sql_query('LASTNAME', 'STUDENTS', '12345') # `%f%` is vectorized v <- c('{vegetable}', '{animal}', '{mineral}', '{animal} and {mineral}') v %f% c(vegetable = 'carrot', animal = 'porpoise', mineral = 'salt') # if the number of replacements is larger than the length of unnamed arguments, # `%f%` will recycle the arguments (and give a warning) c('{} {}', '{} {} {}', '{}') %f% c(0, 1) # > "0 1" "0 1 0" "0"
# order matters when not using a named vector 'the quick {} fox jumped {} the lazy {}' %f% c('brown', 'over', 'dog') # use a named vector to insert values by referencing them in the string gen_sql_query <- function(column, table, id){ query <- "SELECT {col} FROM {tab} WHERE pk = {id}" query %f% c(col = column, tab = table, id = id) } gen_sql_query('LASTNAME', 'STUDENTS', '12345') # `%f%` is vectorized v <- c('{vegetable}', '{animal}', '{mineral}', '{animal} and {mineral}') v %f% c(vegetable = 'carrot', animal = 'porpoise', mineral = 'salt') # if the number of replacements is larger than the length of unnamed arguments, # `%f%` will recycle the arguments (and give a warning) c('{} {}', '{} {} {}', '{}') %f% c(0, 1) # > "0 1" "0 1 0" "0"