0

I'm just getting started with pipes How can I make ifelse() work with pipes

Here is an example code that works

x <- sample(-5:5,10,replace = T)
x
 [1]  0  0  2 -1  1  3  1  3  4 -2


 ifelse( sign(x) >= 0,1,-1)
 [1]  1  1  1 -1  1  1  1  1  1 -1

Here is my unsuccessful attempt to do it with pipes

x |> sign() |> ifelse(. >= 0, 1, -1)

Error in ifelse(sign(x), . >= 0, 1, -1) : unused argument (-1)
mr.T
  • 181
  • 2
  • 13
  • 1
    Related: https://stackoverflow.com/questions/67633022/what-are-the-differences-between-rs-new-native-pipe-and-the-magrittr-pipe/72004083#72004083. This can give you helpful information on what is possible to do with the pipes – Maël Jun 07 '23 at 10:56
  • Thanks, I'll definitely check it out – mr.T Jun 07 '23 at 11:01

2 Answers2

3

You could use curly braces with a function \(.) to pipe a vector like this:

set.seed(7) # reproducibility
x <- sample(-5:5,10,replace = T)
x
#>  [1]  4 -3  1 -4  4  0  2  2 -3  2
x |>
  sign() |>
  {\(.) ifelse(. >= 0, 1, -1)}()
#>  [1]  1 -1  1 -1  1  1  1  1 -1  1

Also make sure to add the () after the function when using a RHS pipe otherwise it returns an error like this:

x |>
  sign() |>
  {\(.) ifelse(. >= 0, 1, -1)}

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

Created on 2023-06-07 with reprex v2.0.2

Quinten
  • 35,235
  • 5
  • 20
  • 53
3

Note that the sign doesn't change the relationship between the input and 0 so drop that. Now (1) put >= into a separate leg or (2) create a list with x as its one element followed by a with or (3) do the same but use an arithmetic expression in place of ifelse or (4) create a function that uses the ifelse.

# 1
x |>
  (`>=`)(0) |>
  ifelse(1, -1)

# 2
x |>
  list(x = _) |>
  with(ifelse(x >= 0, 1, -1))

# 3
x |>
  list(x = _) |>
  with((x >= 0) - (x < 0))

# 4
unity <- function(x) ifelse(x >= 0, 1, -1)
x |>
  unity()

Another possibility is to use magrittr pipes in which case we can write:

library(magrittr)

x %>%
  { ifelse(. >= 0, 1, -1) }
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341