How can we conditionally evaluate a step in a native R |>
pipeline?
This post shows how to do it with magrittr %>%
pipe.
library(dplyr)
do_thing = TRUE
# Works with magrittr syntax leading into the `{ }` expression.
x <- iris %>%
{ if (do_thing) mutate(., Sepal.Length = Sepal.Length + 100) else . } |>
select(Sepal.Length)
# Errors with native pipe leading into the `{ }`
# NB: the placeholder after `mutate(_` is updated
# Error in { :
# function '{' not supported in RHS call of a pipe (<input>:2:3)
x <- iris |>
{ if (do_thing) mutate(_, Sepal.Length = Sepal.Length + 100) else _ } |>
select(Sepal.Length)