Search code examples
rmagrittr

Using magrittr and which


I want to rewrite the following code with pipes from magrittr:

max(diff(which(diff(runif(50)) > 0 )))

My straightforward approach would be:

library(magrittr)
runif(50) %>% diff > 0 %>% which %>% diff %>% max

But this fails due to the (first) which:

runif(50) %>% diff > 0 %>% which

Error in which(.) : argument to 'which' is not logical

I am unsure why this error occurs and why piping to which seems to be different from piping to other functions as the output of "diff > 0" is a logical vector.

On a sidenote, would there be a way to pipe for the comparison, bluntly speaking

 runif(50) %>% diff %>% > 0 

Solution

  • Try:

    runif(50) %>% diff %>% `>`(0) %>% which %>% diff %>% max
    

    Edit: Should probably point out that those are backticks, not quotation marks.