onlyif: Conditionally apply a function to an argument

Description Arguments Value Usage Details Note See Also Examples

Description

This function conditionally applies a function to an argument given a logical condition.

Arguments

condition

Logical statement used to conditionally apply fn to x

fn

A function to apply to x

expr

An expression

x

An object

Value

Either expr if condition is true, otherwise x.

Usage

onlyif(condition, fn, x)

Details

This function can be used to apply a function to a vector containing elements that lie outside the valid domain of fn. The function onlyif differs from ifelse in the sense that it is not vectorized and a closure can be used. For example,

ifelse(length(x) < 10, pad(x, 10 - length(x)), x)

yields the wrong result due to the length of the first argument. The onlyif function is designed for these situations.

onlyif(length(x) < 10, function(x) pad(x, 10 - length(x)), x).

Note that a closure is only required if an expression cannot be evaluated under both a TRUE or FALSE scenario.

The alternative would be to use a conditional block, which can result in improperly scoped code if one is careless.

Note

The interface for this function is experimental. I'm looking for a way to preserve unevaluated expressions. Until then, I don't recommend using the function.

See Also

use_default

Examples

1
2
3
4
5
6
7
x <- 1:5
onlyif(length(x) < 10, pad(x, 10 - length(x)), x)
onlyif(length(x) < 10, function(x) pad(x, 10 - length(x)), x)

# This returns x
x <- 1:20
onlyif(length(x) < 10, function(x) pad(x, 10 - length(x)), x)

zatonovo/lambda.tools documentation built on May 4, 2019, 9:11 p.m.