title: r rolling custom function
body: <p>I am trying to build a rolling take-profit / stop-loss detection function in R using zoo package.</p>
  
  <pre><code>    x &lt;- as.data.frame(rnorm(10000, 0, 1))
      x$cumul &lt;- cumsum(x[, 1])
      plot(x$cumul, type = 'l')
      y &lt;- as.data.frame(x$cumul)
  
      level_break &lt;- function(x, n, z){
      if (min(c(1:nrow(x))[x[, 1] &gt; z]) &lt;= n
          &amp; (min(c(1:nrow(x))[x[, 1] &gt; z]) &lt; min(c(1:nrow(x))[x[, 1] &lt; -z])
             | min(c(1:nrow(x))[x[, 1] &lt; -z]) &gt; n)){
          level &lt;- 1
  
      }else if (min(c(1:nrow(x))[x[, 1] &lt; -z]) &lt;= n
             &amp; (min(c(1:nrow(x))[x[, 1] &lt; -z]) &lt; min(c(1:nrow(x))[x[, 1] &gt; z])
                | min(c(1:nrow(x))[x[, 1] &gt; z]) &gt; n)){
          level &lt;- -1
  
      } else {
          level &lt;- 0
      }
      return(level)
  }
  
  library(zoo)
  yy &lt;- rollapply(data = y$`x$cumul`, width = 1000, align = 'left', function(x) level_break(y, n = 1000, z = 1))
  </code></pre>
  
  <p>I am sure I am making something wrong. Could you please help me understand how to make it work. Or otherwise I would be happy to learn that there is a dedicated function in some package that does exactly what I am doing.</p>
  
  <p>After all clarifications: An ultimate take-profit/stop-loss function: </p>
  
  <pre><code>#################### sl-tp
  
  x &lt;- as.data.frame(rnorm(10000, 0, 1))
  x$cumul &lt;- cumsum(x[, 1])
  plot(x$cumul, type = 'l')
  y &lt;- as.data.frame(x$cumul)
  
  
  level_break &lt;- function(x, n, tp, sl) {
      if (min(c(1:length(x))[x &gt; tp]) &lt;= n
          &amp; (min(c(1:length(x))[x &gt; tp]) &lt; min(c(1:length(x))[x &lt; sl])
             | is.infinite(min(c(1:length(x))[x &lt; sl])) == T)) {
          level &lt;- 1
  
      }else if (min(c(1:length(x))[x &lt; sl]) &lt;= n
             &amp; (min(c(1:length(x))[x &lt; sl]) &lt; min(c(1:length(x))[x &gt; tp])
                | is.infinite(min(c(1:length(x))[x &gt; tp])) == T)) {
          level &lt;- -1
  
      } else {
          level &lt;- 0
      }
      return(level)
  }
  
  library(zoo)
  
  level &lt;- 10
  window &lt;- 1000
  
  start &lt;- Sys.time()
  yy &lt;- rollapply(data = y$`x$cumul`
            , width = window
            , align = 'left'
            , function(x) level_break(x = x, n = window, tp = head(x + level, 1), sl = head(x - level, 1)))
  Sys.time() - start
  
  plot(yy, type = 'l')
  </code></pre>