title: R Error: replacement has length zero
body: <p>I'm trying to identify the nearest position to indicate close position(cP).</p>
  
  <p>Let's say I have the following:</p>
  
  <pre><code>indicator.Trade=c(1,1,0,0,-1,0,0,0,1,1,0,-1,-1)
  cP=c(NA,NA,1,1,NA,-1,NA,NA,1,NA,NA,1,NA)
  
  ## If indicator.Trade[1] is 1, I want to obtain order.book[1,1]=1 and order.book[2,1]=3. 
  ## If indicator.Trade[2] is 1, I want to obtain order.book[1,2]=2 and order.book[2,2]=3.
  
  order.book=matrix(0,nrow=2,ncol=(length(indicator.Trade)-1))
  for(i in 1:(length(indicator.Trade)-1)){
     if( (indicator.Trade[i]==1) ){
         order.book[1,i]=i
         order.book[2,i]=head(which(cP[c((i):(length(indicator.Trade)-1))]==1),1)
     }    else if(indicator.Trade[i]==-1){
         order.book[1,i]=i
         order.book[2,i]=head(which(cP[c((i):(length(indicator.Trade)-1))]==-1),1)
     }    else {
         order.book[1,i]=i
         order.book[2,i]=0
     }
  }
  </code></pre>
  
  <p>But running the code above I get the following error:</p>
  
  <pre><code> in order.book[2, i] = head(which(cP[c((i):(length(indicator.Trade) -  : 
    replacement has length zero
  </code></pre>
  
  <p>I tried substituting manually:</p>
  
  <pre><code>i=1 and i=(length(indicator.Trade)-1) 
  </code></pre>
  
  <p>As suggested in <a href="https://stackoverflow.com/questions/17665164/simple-for-loop-in-r-producing-replacement-has-length-zero-in-r">Simple for loop in R producing &quot;replacement has length zero&quot; in R</a> to check for numeric(0) but that doesn't seem to be the case. What am I missing here?</p>
  
  <p><strong>Edit</strong></p>
  
  <p>I've just realized that</p>
  
  <pre><code>head(which(cP[c(((length(indicator.Trade)-1)):(length(indicator.Trade)-1))]==1),1)
  [1] 1
  </code></pre>
  
  <p>So, my code for finding the correct index position would be wrong. However, I'm still expecting it to run though.</p>