Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use ifelse() with pipes in R

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading