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)
>Solution :
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