Learn R Programming

lambda.tools (version 1.0.9)

onlyif: Conditionally apply a function to an argument

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.

See Also

use_default

Examples

Run this code
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)

Run the code above in your browser using DataLab