Search code examples
rpipingmagrittr

How to feed pipe into an inequality?


This has come up in multiple instances, and I do not know if this current instance is generalizable to the many cases where this arises for me, but I'm hoping an answer may shed some light.

The simplest version of this is when I am doing some data processing and want to perform an evaluation on the result of a pipe. A simple example would be:

> seq(9) %>% > 4
Error: unexpected '>' in "seq(9) %>% >"
> seq(9) %>% . > 4
Error in .(.) : could not find function "."

The desired output would be a logical vector

FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE

In many circumstances I want to evaluate on some piped output but have to assign it and then perform the evaluation for it to work:

seq(9) -> vec
vec > 4

Is there a way to complete these sorts of evaluations within a pipe chain entirely?


Solution

  • You need to use curly braces if you just want to use pipes.

    seq(9) %>% {. > 4}
    
    [1] FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE
    

    I'd recommend using purrr if you're going to be piping these kinds of things, as it will result in a bit more readable code.

    library(purrr)
    
    map_lgl(seq(9), ~.x > 4)
    
    [1] FALSE FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE