Skip to contents

Functions of 1 argument

We start by defining a vector to be of the new vec class

x <- as_vec(1:15)
x
#>  [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15

{vec} provides some helpful vector-operation functions; is_even(a) and is_odd(a)

is_even(6)
#> [1] TRUE
is_even(7)
#> [1] FALSE
is_odd(7)
#> [1] TRUE

These can be used in the regular way

x[is_even(x)]
#> [1]  2  4  6  8 10 12 14

because this is evaluated first

is_even(x)
#>  [1] FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE
#> [13] FALSE  TRUE FALSE

producing the logical vector for regular subsetting.

For vectors of class vec, you can also specify a formula involving arguments

x[~is_even(x)]
#> [1]  2  4  6  8 10 12 14

Or, if you wish to refer to the enclosing vector, you can use a . placeholder

x[~is_even(.)]
#> [1]  2  4  6  8 10 12 14

A new syntax is introduced where a bare function can be used with the effect that x[f] == x[f(x)]

x[is_even]
#> [1]  2  4  6  8 10 12 14
x[is_odd]
#> [1]  1  3  5  7  9 11 13 15

This function can also be used to replace those values for which is_even(x) == TRUE

x[is_even] <- 99
x
#>  [1]  1 99  3 99  5 99  7 99  9 99 11 99 13 99 15

Functions of more than 1 argument

Resetting the vector

x <- as_vec(1:15)
x
#>  [1]  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15

{vec} also provides a two-argument function is_divisible_by(a, b)

is_divisible_by(11, 5)
#> [1] FALSE
is_divisible_by(10, 5)
#> [1] TRUE
is_divisible_by(1:6, 2)
#> [1] FALSE  TRUE FALSE  TRUE FALSE  TRUE

which can be used in the same ways, using explicit arguments

x[is_divisible_by(x, 3)]
#> [1]  3  6  9 12 15
x[~is_divisible_by(x, 3)]
#> [1]  3  6  9 12 15
x[~is_divisible_by(., 3)]
#> [1]  3  6  9 12 15

again because this is evaluated first

is_divisible_by(x, 3)
#>  [1] FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE  TRUE
#> [13] FALSE FALSE  TRUE

For multiple arguments with a bare function, one option would be to pass named arguments to the function via [’s ... argument, e.g.

x[is_divisible_by, n = 3]
#> [1]  3  6  9 12 15

but this is somewhat unclean; the b refers to the function argument and looks too similar to regular [ subsetting.

Alternatively, curry the function; consume one of the arguments

div3 <- function(aa) {
  is_divisible_by(aa, n = 3)
}

x[div3]
#> [1]  3  6  9 12 15

This function can also be used to replace those values for which div3(x) == TRUE

x[div3] <- 99
x
#>  [1]  1  2 99  4  5 99  7  8 99 10 11 99 13 14 99