title: Finding the closest index to a value in R
body: <p>I have a question about finding index values in a vector. </p>
  
  <p>Let's say I have a vector as follows:</p>
  
  <pre><code>vector &lt;- c(1,2,4,6,8,10)
  </code></pre>
  
  <p>And, let's say I have the value '5'. I would like to find the maximum index in "vector" such that it is less than or equal to the value 5. In the case of the example above, this index would be 3 (since 4 is less than or equal to 5). Similarly, if instead I had a vector such as:</p>
  
  <pre><code>vector &lt;- c(1,2,4,5,6,8,10)
  </code></pre>
  
  <p>Then if I were to find a value less than or equal to 5, this index would now be 4 instead of 3.</p>
  
  <p>However, I also want to find the <em>first</em> and <em>last</em> time this index occurs. For example, if I had a vector such as:</p>
  
  <pre><code>vector &lt;- c(1,1,2,2,4,5,5,5,5,6,8,10)
  </code></pre>
  
  <p>Then the first time this index occurs would be 6 and the last time this index occurs would be 9.</p>
  
  <p>Is there a short, one-line method which would allow me to perform this task? Up until now I have been using the function max(which(....)), however I find that this method is extremely inefficient for large datasets since it will literally list hundreds/thousands of values, so I would like to find a more efficient method if possible which can fit in one line.</p>
  
  <p>Thanks in advance.</p>