Search code examples
rmagrittr

which function with magrittr


I don't understand why the combination of magrittr and the which function doesn't work !!

> x <- c(TRUE, TRUE, TRUE, FALSE, TRUE)
> x %>% which(. == TRUE)
[1] 1 2 3 5
> x %>% which(. == FALSE)
[1] 1 2 3 5

The last one is clearly wrong. however this works:

> x %>% (function(s){which(s==TRUE)})
[1] 1 2 3 5
> x %>% (function(s){which(s==FALSE)})
[1] 4

also this works:

> x %>% which
[1] 1 2 3 5
> (!x) %>% which
[1] 4
> 

I guess '.' notation won't work with the equivalent sign '=='

Any idea ? Appreciated in advance


Solution

  • Basic concept of pipe :

    The left-hand side of pipe is the first argument to the function in right hand side.

    So when you do :

    c(1, 2, 3) %>% sum
    #[1] 6
    

    it means you are doing :

    sum(c(1, 2, 3))
    #[1] 6
    

    Similarly, when you do :

    x <- c(TRUE, TRUE, TRUE, FALSE, TRUE)
    x %>% which(. == TRUE)
    #[1] 1 2 3 5
    

    It means you are doing

    which(x, x == TRUE)
    #[1] 1 2 3 5
    

    and

    x %>% which(. == FALSE)
    #[1] 1 2 3 5
    

    is same as

    which(x, x == FALSE)
    #[1] 1 2 3 5
    

    So when using pipes x == TRUE and x == FALSE are treated as second argument to which which is arr.ind.

    You can stop this behavior of pipe which is LHS of pipe as first argument to function in RHS by using {}. In which case you'll get expected output.

    x %>% {which(. == TRUE)}
    #[1] 1 2 3 5
    
    x %>% {which(. == FALSE)}
    #[1] 4
    

    Also note that you don't really need to compare logical values with ==.

    x %>% which
    

    and

    x %>% `!` %>% which
    

    works the same way.