title: Object in algorithm is 'not defined' later in graph
body: <p>I'm having a trouble reproducing the graph for the following code: </p>
  
  <pre><code>ThresholdingAlgo &lt;- function(y,lag,threshold,influence) {
    signals &lt;- rep(0,length(y))
    filteredY &lt;- y[0:lag]
    avgFilter &lt;- NULL
    stdFilter &lt;- NULL
    avgFilter[lag] &lt;- mean(y[0:lag])
    stdFilter[lag] &lt;- sd(y[0:lag])
    for (i in (lag+1):length(y)){
      if (abs(y[i]-avgFilter[i-1]) &gt; threshold*stdFilter[i-1]) {
        if (y[i] &gt; avgFilter[i-1]) {
          signals[i] &lt;- 1;
        } else {
          signals[i] &lt;- -1;
        }
        filteredY[i] &lt;- influence*y[i]+(1-influence)*filteredY[i-1]
      } else {
        signals[i] &lt;- 0
        filteredY[i] &lt;- y[i]
      }
      avgFilter[i] &lt;- mean(filteredY[(i-lag):i])
      stdFilter[i] &lt;- sd(filteredY[(i-lag):i])
    }
    return(list("signals"=signals,"avgFilter"=avgFilter,"stdFilter"=stdFilter))
  }  
  y &lt;- c(1,1,1.1,1,0.9,1,1,1.1,1,0.9,1,1.1,1,1,0.9,1,1,1.1,1,1,1,1,1.1,0.9,1,1.1,1,1,0.9,
     1,1.1,1,1,1.1,1,0.8,0.9,1,1.2,0.9,1,1,1.1,1.2,1,1.5,1,3,2,5,3,2,1,1,1,0.9,1,1,3,
     2.6,4,3,3.2,2,1,1,0.8,4,4,2,2.5,1,1,1)
  
  # Run algo with lag = 30, threshold = 5, influence = 0
  result &lt;- ThresholdingAlgo(y,30,5,0)
  
  # Plot result
  par(mfrow = c(2,1),oma = c(2,2,0,0) + 0.1,mar = c(0,0,2,1) + 0.2)
  plot(1:length(y),y,type="l",ylab="",xlab="") 
  lines(1:length(y),result$avgFilter,type="l",col="cyan",lwd=2)
  lines(1:length(y),result$avgFilter+threshold*result$stdFilter,type="l",col="green",lwd=2)
  lines(1:length(y),result$avgFilter-threshold*result$stdFilter,type="l",col="green",lwd=2)
  plot(result$signals,type="S",col="red",ylab="",xlab="",ylim=c(-1.5,1.5),lwd=2)
  </code></pre>
  
  <p>The graph is suppose to look like this:
  <a href="https://i.stack.imgur.com/KdpF7.jpg" rel="nofollow noreferrer">graph with two lines and shading</a>
  But when I run the code, I get "Error: object 'threshold' not found</p>
  
  <p>My work around is using 
      threshold &lt;- 5</p>
  
  <p>But that gives me a slightly different graph. <a href="https://i.stack.imgur.com/SfGsW.jpg" rel="nofollow noreferrer">second graph, not prefered</a></p>
  
  <p>Question: Why do I have to redefine the threshold in order to get the graph to work? </p>
  
  <p>I pulled the code from this question on Stack. <a href="https://stackoverflow.com/questions/22583391/peak-signal-detection-in-realtime-timeseries-data/22640362">Peak signal detection in realtime timeseries data</a></p>