title: How to find the difference between a value and its closest value in a vector in R?
body: <p>I have a vector like below:</p>
  
  <pre><code>x= c(1,23,4,15,8,17,21)
  </code></pre>
  
  <p>after sort values in vector we have:</p>
  
  <pre><code>c(1,4,8,15,17,21,23)
  </code></pre>
  
  <p>my required output is :</p>
  
  <pre><code>c(3, 3, 4, 2, 2, 2, 2) 
  </code></pre>
  
  <p>Which contains the difference between the value and its closest value.</p>
  
  <p>But if I want to have output without sorting, is there any solution? I need an out put like c(3,2,3,2,4,2,2) to know which sample has biggest value in output table (here 5th value is the result)</p>