4

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)
Lief Esbenshade
  • 793
  • 4
  • 13
  • 1
    Native Pipe use different placeholder syntax, which is `_`. [See this](https://stackoverflow.com/a/72086492/10858321) for full details comparison. – shafee Jul 29 '23 at 05:41
  • Changing the placeholder doesn't help. The error is still `Error in { : function '{' not supported in RHS call of a pipe (:2:3)` – Lief Esbenshade Jul 29 '23 at 05:48
  • What exactly do you want to do? Your code looks like you might want to change some column values based on a condition, which might be able to do without your if command. So sharing your use case would be helpful. – deschen Jul 29 '23 at 05:49
  • I use standardized data cleaning pipelines when processing lots of similar files. Its very handy to be able to call a single function to run all the cleaning, but then have params to turn off certain steps that might cause an issue with a file that is slightly different from the others. – Lief Esbenshade Jul 29 '23 at 06:02

1 Answers1

2

Note that the placeholder _ is limited to one usage (see also What are the differences between R's new native pipe |> and the magrittr pipe %>%?).

However, you can use an anonymous function.

x <- iris |> 
    {\(.) if (do_thing) mutate(., Sepal.Length = Sepal.Length + 100) else . }() |> 
    select(Sepal.Length)
Jan
  • 2,245
  • 1
  • 2
  • 16
  • Thanks! Why are the final closing parens needed in `... else . }()`. I had almost gotten this syntax, but omitted that paren pair and saw the `function '{' not supported in RHS call of a pipe (:2:3)` error message. – Lief Esbenshade Jul 29 '23 at 07:05
  • This is the call of your anonymous function. Without these parentheses, you would only have defined the function. – Jan Jul 29 '23 at 07:07
  • Of course! Now it makes sense. Thank you – Lief Esbenshade Jul 29 '23 at 07:10