3

I am wondering how to use the base |> pipe in place of tidyverse's %>% in a situation where there are conditional elements of a dplyr chain. When I try to following code with |>, I get an error:

Error: function '{' not supported in RHS call of a pipe

Example with Tidyverse

library(tidyverse)

condition = FALSE

mtcars %>%
  { if(condition == TRUE)
    mutate(., mpg = mpg*1000)
    else . }

Example with base R pipe (causes error):

mtcars |>
  { if(condition == TRUE)
    mutate(., mpg = mpg*1000)
    else . }
acircleda
  • 673
  • 4
  • 13

3 Answers3

4

Call it via an unnamed function. This is needed as you are using the placeholder on two positions.

mtcars |>
  {\(.) if(condition == TRUE)
    mutate(., mpg = mpg*1000)
    else . }()

Have also a look at What are the differences between R's new native pipe |> and the magrittr pipe %>%?.

GKi
  • 37,245
  • 2
  • 26
  • 48
  • That works, but it's so....ugly ;) – acircleda Apr 07 '23 at 20:41
  • Maybe have a look at [Does the Bizarro pipe ->.; have disadvantages making it not recommended for use?](https://stackoverflow.com/questions/67868289/) as another possibility. – GKi Apr 11 '23 at 06:50
1

Can you put the condition inside of mutate?

mtcars |>
  mutate(mpg = if (condition) mpg*1000 else mpg)
#                      mpg cyl  disp  hp drat    wt  qsec vs am gear carb
# Mazda RX4           21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
# Mazda RX4 Wag       21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
# Datsun 710          22.8   4 108.0  93 3.85 2.320 18.61  1  1    4    1
# Hornet 4 Drive      21.4   6 258.0 110 3.08 3.215 19.44  1  0    3    1
# ...
r2evans
  • 141,215
  • 6
  • 77
  • 149
0

Try within.

mtcars |> within(mpg[condition] <- mpg[condition]*1e3)

Demo

condition <- FALSE
mtcars |> 
  within(mpg[condition] <- mpg[condition]*1e3) |>
  head(3)
#                mpg cyl disp  hp drat    wt  qsec vs am gear carb
# Mazda RX4     21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
# Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
# Datsun 710    22.8   4  108  93 3.85 2.320 18.61  1  1    4    1

condition <- TRUE
mtcars |> 
  within({
    mpg[cond] <- mpg[cond]*1e3
    am[cond] <- am[cond]*-999
  }) |>
  head(3)
#                 mpg cyl disp  hp drat    wt  qsec vs   am gear carb
# Mazda RX4     21000   6  160 110 3.90 2.620 16.46  0 -999    4    4
# Mazda RX4 Wag 21000   6  160 110 3.90 2.875 17.02  0 -999    4    4
# Datsun 710    22800   4  108  93 3.85 2.320 18.61  1 -999    4    1
jay.sf
  • 60,139
  • 8
  • 53
  • 110