title: Nested tables and calculating summary statistics with confidence intervals in R
body: <p>This question is about the statistical program <strong>R</strong>.</p>
  
  <h3>Data</h3>
  
  <p>I have a data frame, <code>study_data</code>, that has 100 rows, each representing a different person, and three columns, <code>gender</code>, <code>height_category</code>, and <code>freckles</code>. The variable <code>gender</code> is a factor and takes the value of either "male" or "female". The variable <code>height_category</code> is also a factor and takes the value of "tall" or "short". The variable <code>freckles</code> is a continuous, numeric variable that states how many freckles that individual has.</p>
  
  <p>Here are some example data (thanks to Roland for this):</p>
  
  <pre><code>set.seed(42)
  DF &lt;- data.frame(gender=sample(c("m","f"),100,T),
        height_category=sample(c("tall","short"),100,T),
        freckles=runif(100,0,100))
  </code></pre>
  
  <h3>Question 1</h3>
  
  <p>I would like to create a nested table that divides these patients into "male" versus "female", further subdivides them into "tall" versus "short", and then calculates the number of patients in each sub-grouping along with the median number of freckles with the lower and upper 95% confidence interval.</p>
  
  <h3>Example</h3>
  
  <p>The table should look something like what is shown below, where the # signs are replaced with the appropriate calculated results.</p>
  
  <pre><code>gender height_category n median_freckles LCI UCI
  
  male              tall #               #   #   #
                   short #               #   #   #
  female            tall #               #   #   #
                   short #               #   #   #
  </code></pre>
  
  <h3>Question 2</h3>
  
  <p>Once these results have been calculated, I would then like to create a bar graph. The y axis will be the median number of freckles. The x axis will be divided into male versus female. However, these sections will be subdivided by height category (so there will be a total of four bars in groups of two). I'd like to overlay the 95% confidence bands on top of the bars.</p>
  
  <h3>What I've tried</h3>
  
  <p>I know that I can make a nested table using the <code>MASS</code> library and <code>xtabs</code> command:</p>
  
  <pre><code>ftable(xtabs(formula = ~ gender + height_category, data = study_data))
  </code></pre>
  
  <p>However, I'm not sure how to incorporate calculating the median of the number of freckles into this command and then getting it to show up in the summary table. I'm also aware that <code>ggplot2</code> can be used to make bar graphs, but am not sure how to do this given that I can't calculate the data that I need in the first place.</p>