Is there a function that does the following ?
library(dplyr)
cond = T
if (cond == T) {
print('Hello')
}
# [1] "Hello"
# How can I achieve the same as above with a pipe ?
print('Hello') %>% function_if(cond)
I know the purrr::when
and ifelse
functions but they don't work here.
CodePudding user response:
Admittedly, I don't see utility in this ... but
function_if <- function(data, expr) if (isTRUE(expr)) force(data)
cond <- TRUE
print('Hello') %>%
function_if(cond)
# [1] "Hello"
print('Hello') %>%
function_if(cond) %>%
class()
# [1] "Hello" # <-- action of 'print'
# [1] "character" # <-- output from 'class', to show that
print('Hello') %>% # <-- this never happens here
function_if(FALSE) %>%
class()
# [1] "NULL" # <-- output from 'class', no 'print' output
I don't know that I would ever use this, to be candid.
The way it works: data
(which can be any object) is defined lazily here. The order of execution here is: %>%
, function_if
, and only if isTRUE(expr)
, it forces evaluation of data
. If it was true, then data
is evaluated and returned; if it was not true, then function_if
does not force data, so its lazy presence is never instantiated, and NULL
is implicitly returned instead.
Perhaps a better name for this function would be stoppipe_if_not
, meaning that all data-flow in the pipe (whether data.frame
or anything else) will not be passed along if the cond
ition is not precisely TRUE
.