format-string: Pass variables into strings

Description Usage Arguments Examples

Description

Pass variables into strings using pairs of curly brackets to identify points of insertion.

Usage

1
string %f% args

Arguments

string

A character vector

args

A (possibly named) atomic vector

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
# 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"
  

stringformattr documentation built on Dec. 17, 2017, 9:03 a.m.