Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use base R pipe in conditional dplyr chain

Tags:

r

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 . }
like image 614
acircleda Avatar asked Oct 19 '25 23:10

acircleda


1 Answers

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 %>%?.

like image 84
GKi Avatar answered Oct 22 '25 15:10

GKi