title: Linear model of geom_histogram data
body: <p>I'm working with dataset in which I have continuous variable x and categorical variables y and z. Something like this:</p>
  
  <pre><code>set.seed(222)
  df = data.frame(x = c(0, c(1:99) + rnorm(99, mean = 0, sd = 0.5), 100),
             y = rep(50, times = 101)-(seq(0, 50, by = 0.5))+rnorm(101, mean = 30, sd = 20),
             z = rnorm(101, mean = 50, sd= 10))
  
  df$positive.y = sapply(df$y,
                           function(x){
                             if (x &gt;= 50){"Yes"} else {"No"}
                           })
  
  df$positive.z = sapply(df$z,
                         function(x){
                           if (x &gt;= 50){"Yes"} else {"No"}
                         })
  </code></pre>
  
  <p>Then using this dataset I can create histograms to see either there is correlation between variables <em>x</em> and <em>positive.y(z)</em>. With 10 bins it is clear that x correlates with positive.y, but not with positive.z:</p>
  
  <pre><code>ggplot(df,
         aes(x = x, fill = positive.y))+
    geom_histogram(position = "fill", bins = 10)
  
  ggplot(df,
         aes(x = x, fill = positive.z))+
    geom_histogram(position = "fill", bins = 10)
  
  </code></pre>
  
  <p>Now from this I want two things:</p>
  
  <ol>
  <li><p>Extract the actual data points to supply them to corr.test() function or something like that.</p></li>
  <li><p>Add geom_smooth(method = "lm") to plot I have.</p></li>
  </ol>
  
  <p>I tried to add "bin" column to the df, like this:</p>
  
  <pre><code>df$bin = sapply(df$x,
                  function(x){
                    if (x &lt;= 10){1}
                    else if (x &gt; 10 &amp; &lt;= 20) {20}
                    else if .......
                  })
  </code></pre>
  
  <p>Then using tapply() count number of "Yes" and "No" for each df$bin, and convert it to the %.
  But in this case each time I change number of bins at histogram, I have to re-write and re-run this part of code which is tedious and consumes a lot of computer time if dataset is large.</p>
  
  <p>Is there a more straightforward way to achieve the same result?</p>