This vingette presents advanced operations included in string_magic. There are four parts:

By default the function string_magic returns a plain character vector. In this vignette it is sometimes nicer to apply the function base::cat to display string_magic results containing newlines. Ths function cat_magic does exactly that and we will use it from time to time.

Group-wise operations

In string_magic, the operations split and extract keep a memory of the strings that were split (i.e. they provide multiple results for each initial string element).

Use the tilde operator, of the form ~(op1, op2), to apply operations group-wise, to each of the split strings. Better with an example.

x = c("Oreste, Hermione", "Hermione, Pyrrhus", "Pyrrhus, Andromaque")
string_magic("Troubles ahead: {', 'split, ~(' loves 'collapse), enum ? x}.")
#> [1] "Troubles ahead: Oreste loves Hermione, Hermione loves Pyrrhus and Pyrrhus loves Andromaque."

Almost all operations can be applied group-wise (although only operations changing the order or the length of the strings really matter, see the dedicated section).

Conditional operations

There are two operators to apply operations conditionally: if and vif, the latter standing for verbatim if.

if statement

The syntax of if is if(cond ; ops_true ; ops_false) with cond a condition (i.e. logical operation) on the value being interpolated, ops_true a comma-separated sequence of operations if the condition is TRUE and ops_false an optional a sequence of operations if the condition is FALSE.

The condition cond accepts the following special values:

  • . (the dot): refers to the current vector
  • .nchar or .C: represent the number of characters of the current vector (equivalent to nchar(.))
  • .len or .N.: represent the length of the current vector (equivalent to length(.))

Ex.1: Let’s take a sentence, delete words of less than 4 characters, and trim words of 7+ characters.

x = "Songe Céphise à cette nuit cruelle qui fut pour tout un peuple une nuit éternelle"
string_magic("{' 'split, if(.nchar<=4 ; nuke ; 7 shorten), collapse ? x}")
#> [1] "Songe Céphise cette cruelle peuple éternel"

Let’s break it down. First the sentence is split w.r.t. spaces (command ' 'split), leading to a vector of words. Then we use the special variable .nchar in if’s condition to refer to the number of characters of the current vector (the words). The words with less than 4 characters are nuked (i.e. removed), and the other words are trimmed at 7 characters (7 Shorten). Finally the modified vector of words is collapsed with the command collapse, leading to the result.

In Ex.1 the condition led to a vector of length greater than 1 (length = number of words), triggerring element-wise operations.

If a condition leads to a result of length 1, then the operations are applied to the full string vector. Contrary to element-wise conditions for which operations modifying the length of the vectors are forbidden (apart from nuking), such operations are fine in full-string conditions.

Ex.2: we write the sum of several elements, if the vector is longer than 4, we replace all remaining elements with an ellispsis.

# same expression for two values of x give different results
x_short = string_magic("x{1:4}")
# the false statement is missing: it means that nothing is done is .N<=4
string_magic("y = {if(.N>4 ; 3 first, '...'insert.right), ' + 'c ? x_short}")
#> [1] "y = x1 + x2 + x3 + x4"

x_long = string_magic("x{1:10}")
string_magic("y = {if(.N>4 ; 3 first, '...'insert.right), ' + 'c ? x_long}")
#> [1] "y = x1 + x2 + x3 + ..."

In this example, the operations applied are:

  • short vector: string_magic("y = {' + 'c ? x_short}")
  • long vector: string_magic("y = {3 first, '...'insert.right, ' + 'c ? x_long}")

Verbatim if statement

For vif, the syntax is vif(cond ; verb_true ; verb_false) with verb_true a verbatim value with which the vector will be replaced if the condition is TRUE. This is similar for verb_false. The condition works as in if.

As for the if operator, you can use the special values ".", .len, .N, .nchar and .C in the condition. On top of this, you can use '.' to refer to the current value in verb_true and verb_false, as illustrated by the following example.

Ex.3: we want to replace all values lower than 10 by the the string “<10”, and then create an enumeration.

pval = c(1e-20, 0.15, 0.5)
cat_magic("pvalues: {vif(.<1e-16 ; <1e-16 ; {%05f ? .}), align.right ? pval}", 
          .sep = "\n")
#> pvalues:   <1e-16
#> pvalues: 0.150000
#> pvalues: 0.500000

In this example, the condition is of the same length as the vector, so an element-wise operation is triggered. Note that we use '.' to refer to pval in the condition. Elements lower than 1e-16 are replaced with the string "<1e-16". Other elements are replaced with {%05f?.}. This string contains the interpolation delimiters, interpolation applies. The dot, '.', now refers to the values of pval respecting the condition. And sprintf formatting is applied (%05f). After this, we right align the results.

Conditions of length 1 apply the replacement to the full vector. Knowing this, let’s redo Ex.2 differently:

x = string_magic("x{1:10}")
string_magic("y = {vif(.N>4 ; {first?x} + ... + {last?x} ; {' + 'c ? x}) ? x}")
#> [1] "y = x1 + ... + x10"

Let’s break it down. If the length of the vector is greater than 4 (here it’s 10), then the full string is replaced with "{first?x} + ... + {last?x}". Since this string contains curly brackets, interpolation applies. Hence we obtain the string "x1 + ... + x10". Finally, this is collated to "y = " leading to the result.

If the vector were of length lower than 4, it would have been replaced with "{' + 'collapse?x}", which will be interpolated.

Special interpolation: if-else

Using an ampersand ("&") as the first character of an interpolation leads to an if-else operation. Using two ampersands ("&&") leads to a slightly different operation described at the end of this section.

Regular if-else: “&”

The syntax is as follows: {&cond ; verb_true ; verb_false} with cond a condition (i.e. logical operation), verb_true a verbatim value with which the vector will be replaced if the condition is TRUE and verb_false an optional verbatim value with which the vector will be replaced if the condition is FALSE. If not provided, verb_false is considered to be the empty string unless the operator is the double ampersand described (&&) at the end of this section.

Note that in cond, you can use the function len, an alias to length.

Ex.1: we take a vector and compose a message depending on its length. If its length is lower than 10 then we write the message "x is short", otherwise we write "x is long", and insert "very" depending on the number of digits.

x = 1:5
string_magic("x is {&len(x)<10 ; short ; {`log10(.N)-1`times, ''c ! very }long}")
#> [1] "x is short"

x = 1:50
string_magic("x is {&len(x)<10 ; short ; {`log10(.N)-1`times, ''c ! very }long}")
#> [1] "x is long"

x = 1:5000
string_magic("x is {&len(x)<10 ; short ; {`log10(.N)-1`times, ''c ! very }long}")
#> [1] "x is very very long"

If a condition leads to a result of length 1, the full string is replaced by the verbatim expression. Further, this expression will be interpolated if requested. This was the case in Ex.1 where verb_false was interpolated.

If the condition uses a variable, in later interpolations you can refer to the first variable present in the condition with ‘.’, and use ‘.len’ or ‘.N’ to refer to its length.

If the condition’s length is greater than 1, then each logical values equal to TRUE is replaced by verb_true, and FALSE values are replaced with verb_false. There can be interpolation on the values verb_true and verb_false. In that case the interpolation must result into a vector of either length 1 or a length equal to the condition. Then element-wise replacements are made, a la base::ifelse.

Ex.2: illustration of element-wise replacements.

x = 1:4
y = letters[1:4]
string_magic("{&x %% 2 ; odd ; {y}}")
#> [1] "odd" "b"   "odd" "d"

In that example, when x is odd, it is replaced with "odd", and when even it is replaced with the elements of y.

if-else with automatic filling

Using the two ampersands operator (&&) is like the simple ampersand version but the default for verb_false is the variable used in the condition itself. So the syntax is {&&cond ; verb_true} and it does not accept verb_false.

Ex.3: let’s write the integer i in letters when equal to 3 only.

i = 3 
string_magic("i = {&&i == 3 ; three}")
#> [1] "i = three"

i = 5
string_magic("i = {&&i == 3 ; three}")
#> [1] "i = 5"

When the condition is of length 1: the full vector is replaced. When the condition is of the length of the vector, an element-wise replacement is triggered, like in example 3.

Special interpolation: Pluralization

There is advanced support for pluralization which greatly facilitates the writing of messages in natural language.

Pluralization: Principles

There are two ways to pluralize: over length or over value. To trigger a “pluralization” interpolation use as first character:

  • # to pluralize over the value of a variable (see Ex.1)
  • $ to pluralize over the length of a variable (see Ex.2)

Ex.1: we add an ending ‘s’ based on a number.

x = 5
string_magic("I bought {N?x} book{#s}.")
#> [1] "I bought five books."

x = 1
string_magic("I bought {N?x} book{#s}.")
#> [1] "I bought one book."

The syntax is {#plural_ops ? variable} or {#plural_ops} where plural_ops are specific pluralization operations which will be described below. The pluralization is perfomed always with respect to the value of a variable.

You can either add the variable explicitly ({#plural_ops ? variable}) or refer to it implicitly ({#plural_ops}). If implicit, then the algorithm will look at the previous variable that was interpolated and pluralize over it. This is exaclty what happens in Ex.1 where x was interpolated in {N?x} and the plural operation s (in {#s}) applies to x. It would have been equivalent to have {#s ? x}. If a variable wasn’t interpolated before, then the next interpolated variable will be used (see Ex.2). If no variable is interpolated at all, an error is thrown.

Ex.2: we add an ending ‘s’ and conjugate the verb ‘be’ based on the length of a vector.

x = c("J.", "M.")
string_magic("My BFF{$s, are} {enum?x}!")
#> [1] "My BFFs are J. and M.!"

x = "J."
string_magic("My BFF{$s, are} {enum?x}!")
#> [1] "My BFF is J.!"

As you can notice in Ex.2, you can chain operations (here 's' and 'are'). In that case a whitespace is automatically added between them.

Now let’s come to the specific pluralization operations, which are different from regular operations.

Pluralization: Regular operations

s, es

Adds an "s" (or "es") if it is plural (> 1), nothing otherwise. Accepts the option 0 or zero which treats a 0-length or a 0-value as plural.

nfiles = 1
string_magic("We've found {#n.no ? nfiles} file{#s}.")
#> [1] "We've found 1 file."

nfiles = 0
string_magic("We've found {#n.no ? nfiles} file{#s}.")
#> [1] "We've found no file."

nfiles = 0
string_magic("We've found {#n.no ? nfiles} file{#s.0}.")
#> [1] "We've found no files."

nfiles = 4
string_magic("We've found {#n.no ? nfiles} file{#s.0}.")
#> [1] "We've found 4 files."

y or ies

Adds an ‘y’ if singular and ‘ies’ if plural (>1). Accepts the option 0 or zero which treats a 0-length or a 0-value as plural.

ndir = 1
string_magic("We've found {ndir} director{#y}.")
#> [1] "We've found 1 directory."

ndir = 5
string_magic("We've found {ndir} director{#y}.")
#> [1] "We've found 5 directories."

ndir = 1
string_magic("We've found {ndir} director{#ies}.")
#> [1] "We've found 1 directory."

enum

Enumerates the elements (see help for the regular operation enum).

fruits = c("apples", "oranges")
string_magic("The fruit{$s ? fruits} I love {$are, enum}.")
#> [1] "The fruits I love are apples and oranges."

fruits = "apples"
string_magic("The fruit{$s ? fruits} I love {$are, enum}.")
#> [1] "The fruit I love is apples."

n, N, len, Len

Add the number of elements ("len") or the value ("n") of the variable as a formatted number or in letters (upper case versions). Accepts the options letter (to write in letter) and upper (to uppercase the first letter).

You can also pass the options no or No, which replace the 0 values with “no”/“No”. Alternatively, pass a free-form argument to be used in lieu of 0 values.

nfiles = 5
string_magic("{#N.upper.No ? nfiles} file{#s, are} compromised.")
#> [1] "Five files are compromised."

nfiles = 1
string_magic("{#N.upper.No ? nfiles} file{#s, are} compromised.")
#> [1] "One file is compromised."

nfiles = 0
string_magic("{#N.upper.No ? nfiles} file{#s, are} compromised.")
#> [1] "No file is compromised."

# Using free-form arguments
nfiles = 5
string_magic("{#'Absolutely no'N.upper ? nfiles} file{#s, are} compromised.")
#> [1] "Five files are compromised."

nfiles = 0
string_magic("{#'Absolutely no'N.upper ? nfiles} file{#s, are} compromised.")
#> [1] "Absolutely no file is compromised."

nth, ntimes

Writes the value of the variable as an order (nth) or a frequence (ntimes). Accepts the option letter to write the numbers in letters (uppercase version of the operator does the same).

n = 2
string_magic("Writing the same sentence {#Ntimes ? n} is unnecessary.")
#> [1] "Writing the same sentence twice is unnecessary."

is, or any verb

Conjugates any English verb appropriately depending on context. Any command that is not recognized as one of the commands previously described is treated as a verb.

Simply add an upper case first to upper case the conjugated verb.

Multiple verbs are illustrated in the example below. It also anticipaed the conditional statements described in the next section.

Ex.3: multiple verbs and conditional statements.

pple = c("Francis", "Henry")
cat_magic("{$enum, is, (a;) ? pple} tall guy{$s}.",
        "{$(He;They), like} to eat donuts.",
        "When happy, at the pub {$(he;they), goes}!",
        "{$Don't, (he;they)} have wit, {$(he;they)} who {$try}?", .sep = "\n")
#> Francis and Henry are tall guys.
#> They like to eat donuts.
#> When happy, at the pub they go!
#> Don't they have wit, they who try?

pple = "Francis"
cat_magic("{$enum, is, (a;) ? pple} tall guy{$s}.",
        "{$(He;They), like} to eat donuts.",
        "When happy, at the pub {$(he;they), goes}!",
        "{$Don't, (he;they)} have wit, {$(he;they)} who {$try}?", .sep = "\n")
#> Francis is a tall guy.
#> He likes to eat donuts.
#> When happy, at the pub he goes!
#> Doesn't he have wit, he who tries?

Pluralization: Conditional statements

On top of the previous operations, there is a special operation allowing to add verbatim text depending on the situation. The syntax is as follows:

  • (s1;s2): adds verbatim ‘s1’ if singular and ‘s2’ if plural (>1)
  • (s1;s2;s3): adds verbatim ‘s1’ if zero, ‘s2’ if singular (=1) and ‘s3’ if plural
  • (s1;;s3): adds verbatim ‘s1’ if zero, ‘s3’ if singular or plural (i.e. >=1)

These case-dependent verbatim values are interpolated (if appropriate). In these interpolations you need not refer explicitly to the variable for pluralization interpolations.

x = 0
string_magic("{#(Sorry, nothing found.;;{#N.upper} match{#es, were} found.)?x}")
#> [1] "Sorry, nothing found."

x = 1
string_magic("{#(Sorry, nothing found.;;{#N.upper} match{#es, were} found.)?x}")
#> [1] "One match was found."

x = 3
string_magic("{#(Sorry, nothing found.;;{#N.upper} match{#es, were} found.)?x}")
#> [1] "Three matches were found."

Direct access to the current time and a timer facility

Current date and time

You can refer to the current date or the current time with the special variables .date and .now:

  • .date is equivalent to Sys.date()
  • .now is equivalent to Sys.time()

Here is an example where we display the day:

string_magic("This message has been written on {.date}.")
#> [1] "This message has been written on 2024-06-20."

On top of this, you can use .now as a function whose sole argument provides the format of the time. The format follows base::strptime (see ?strptime). In the following example, we display the day, month and the hour:

string_magic("This message has been written on {.now('%A %B at %Hh%M')}.")
#> [1] "This message has been written on jeudi juin at 11h20."

Timer

Timers can be very useful inside code to find choke points and debug. stringmagic offers a simple system:

  • first set the timer anywhere with timer_magic()
  • within *_magic functions, display the elapsed time in three possible special variables:
    • .timer: displays the elapsed time and resets the timer
    • .timer_lap: displays the elapsed time and does not reset the timer
    • .timer_total: displays the elapsed time since the timer_magic() call

Here is an example where we time a few computations within a function:

rnorm_crossprod = function(n, mean = 0, sd = 1){
  # we set the timer
  timer_magic()
  # we compute some stuff
  x = rnorm(n, mean, sd)
  # we can report the time with .timer
  message_magic("{10 align ! Generation}: {.timer}")
  
  res = x %*% x
  message_magic("{10 align ! Product}: {.timer}",
                "{10 align ! Total}: {.timer_total}", .sep = "\n")
  res
}

rnorm_crossprod(1e5)
#> Generation:        3.6ms
#> Product   :        1.9ms
#> Total     :        5.6ms
#>          [,1]
#> [1,] 100576.3

Note that timer is precise at +/- 1ms (this is due to its very simple interface), and hence should not be used to time code chunks with very short execution times.

We could refine by trigerring the messages only when debugging. We can do that by using the argument .trigger:

rnorm_crossprod = function(n, mean = 0, sd = 1, debug = FALSE){
  # we set the timer
  timer_magic()
  # we compute some stuff
  x = rnorm(n, mean, sd)
  # we can report the time with .timer
  message_magic("{10 align ! Generation}: {.timer}", .trigger = debug)
  
  res = x %*% x
  message_magic("{10 align ! Product}: {.timer}",
                "{10 align ! Total}: {.timer_total}", 
                .sep = "\n", .trigger = debug)
                
  res
}

# timer not shown
rnorm_crossprod(1e5)
#>          [,1]
#> [1,] 100499.5

# timers shown thanks to the argument
rnorm_crossprod(1e5, debug = TRUE)
#> Generation:        3.4ms
#> Product   :        1.0ms
#> Total     :        4.4ms
#>         [,1]
#> [1,] 99206.3