title: Create a subset that is balanced across multiple variables
body: <p>To illustrate my question, a dummy example: I have a data set with 16 rows (these represent trials) and 3 columns (trial difficulty, label X, and label Y).  Label X is a factor with 4 levels (1–4), and label Y is a factor with 2 levels ("female", "male").  For example:</p>
  
  <pre><code>        difficulty    X    Y
  trial1   3.0           1    male
  trial2   1.4           1    male
  trial3   2.1           1    female
  trial4   1.5           1    female
  trial5   0.3           2    male
  trial6   1.2           2    male
  trial7   3.0           2    female
  trial8   1.6           2    female
  trial9   0.8           3    male
  trial10  1.4           3    male
  trial11  2.8           3    female
  trial12  1.5           3    female
  trial13  0.3           4    male
  trial14  1.2           4    male
  trial15  3.0           4    female
  trial16  1.6           4    female
  </code></pre>
  
  <p>I should like to create a subset of 8 trials from the total of 16 trials; a subset that should adhere to the following criteria:</p>
  
  <ol>
  <li>there is an equal number of trials within the four levels of label X</li>
  <li>there is an equal number of trials within the two levels of label Y (and there should also be an equal number of trials for each level of label Y within the four levels of label X)</li>
  <li>the trial difficulty variable (numeric, ranging from 0 to 3) should be as close as possible to 1.5</li>
  </ol>
  
  <p>For my example, the ideal set in this dummy example would be:</p>
  
  <pre><code>        difficulty    X    Y
  trial2   1.4           1    male
  trial4   1.5           1    female
  trial6   1.2           2    male
  trial8   1.6           2    female
  trial10  1.4           3    male
  trial12  1.5           3    female
  trial14  1.2           4    male
  trial16  1.6           4    female
  </code></pre>
  
  <p>This subset has 2 trials per level of X, and an equal number of females and males for each level of X, while all trials have a difficulty value that is as close as possible to 1.5.</p>
  
  <p>My attempts have been to use many nested <code>while</code> and <code>if</code> loops, but am not sure how to check for two variables at the same time (at the moment I'm looping until X is fulfilled, then looping until Y is fulfilled, then looping until X is fulfilled again, etc.).  Would this be the right approach, or would there be a more sensible way of doing this?</p>