Skip to content

Instantly share code, notes, and snippets.

@favstats
Forked from benjaminguinaudeau/do_if.R
Last active May 3, 2019 16:46
Show Gist options
  • Save favstats/3e1d8b65a019b24344b7b3dea6002a0b to your computer and use it in GitHub Desktop.
Save favstats/3e1d8b65a019b24344b7b3dea6002a0b to your computer and use it in GitHub Desktop.
#' A pipable if statement
#'
#' This function allows to create an if statement that can be used within a pipable workflow
#'
#' @importFrom magrittr %>%
#' @importFrom rlang parse_expr
#' @param .data tibble
#' @param condition logical test
#' @param call a formula descibing a pipe to be evaluated if condition is \code{code}
#' @examples
#' any_condition <- T
#'
#' mtcars %>%
#' do_if(any_condition, ~{
#' .x %>%
#' dplyr::filter(cyl == 6) %>%
#' dplyr::mutate(x = disp > 170)
#' })
#' @export
do_if <- function(.data, condition, call){
if(condition){
.x <- .data
call_str <- call %>%
as.character %>%
.[2]
out <- eval(rlang::parse_expr(call_str))
return(out)
} else {
return(.data)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment