splitting a continuous variable into groups of equal number of elements - return numeric vector from bin values
<p>I have a continuous variable that I want to split into bins, returning a numeric vector (of length equal to my original vector) whose values relate to the values of the bins.  Each bin should have roughly the same number of elements.</p>

<p>This question: <a href="https://stackoverflow.com/questions/6104836/splitting-a-continuous-variable-into-equal-sized-groups">splitting a continuous variable into equal sized groups</a> describes a number of techniques for related situations.  For instance, if I start with</p>

<pre><code>x = c(1,5,3,12,5,6,7)
</code></pre>

<p>I can use <code>cut()</code> to get:</p>

<pre><code>cut(x, 3, labels = FALSE)
[1] 1 2 1 3 2 2 2
</code></pre>

<p>This is undesirable because the values of the factor are just sequential integers, they have no direct relation to the underlying original values in my vector.</p>

<p>Another possibility is <code>cut2</code>: for instance:</p>

<pre><code>library(Hmisc)
cut2(x, g = 3, levels.mean = TRUE)
[1] 3.5 3.5 3.5 9.5 3.5 6.0 9.5
</code></pre>

<p>This better because now the return values relate to the values of the bins.  It is still less than ideal though since:</p>

<ul>
<li>(a) it yields a factor which then needs to be converted to numeric (see, <a href="https://stackoverflow.com/questions/3418128/how-to-convert-a-factor-to-an-integer-numeric-without-a-loss-of-information">e.g.</a>), which is both slow and awkward code wise.</li>
<li>(b) Ideally I'd like to be able to choose whether to use the top or bottom end points of the intervals, instead of just the means.</li>
</ul>

<p>I know that there are also options using regex on the factors returns from <code>cut</code> or <code>cut2</code> to get the top or bottom points of the intervals.  These too seem overly cumbersome.</p>

<p>Is this just a situation that requires some not-so-elegant hacking?  Or, is there some easier functionality to accomplish this?</p>

<p><strong>My current best effort is as follows:</strong></p>

<pre><code>MyDiscretize = function(x, N_Bins){
    f = cut2(x, g = N_Bins, levels.mean = TRUE)
    return(as.numeric(levels(f))[f])
}
</code></pre>

<p>My goal is to find something faster, more elegant, and easily adaptable to use either of the endpoints, rather than just the means.</p>

<hr>

<p><strong>Edit:</strong> </p>

<p>To clarify: my desired output would be:</p>

<ul>
<li><p>(a) an equivalent to what I can achieve right now in the example with <code>cut2</code> but without needing to convert the factor to numeric.</p></li>
<li><p>(b) if possible, the ability to also easily chose to use either of the endpoints of the interval, instead of the midpoint.</p></li>
</ul>