title: How to extract the min/max values in a dataframe to display data as a ribbon?
body: <p>I have several sets of data stored in a data frame. For the sake of this question, I provide below a way to generate this data frame, but IRL, I only have the <code>merged</code> data frame, not the intermediate ones.</p>
  
  <pre><code>x &lt;- seq.POSIXt(from = strptime("1970-01-01 00:00:00", format = "%Y-%m-%d %H:%M:%S"),
                  to = strptime("1970-01-01 00:05:00", format = "%Y-%m-%d %H:%M:%S"),
                  by = "10 sec")
  
  x &lt;- rep(x, each = 3)
  y &lt;- c()
  
  set.seed(1)
  
  for (i in 1:length(x)) {
    y &lt;- c(y, runif(1, min = 0, max = i))
  }
  
  my.data.frame1 &lt;- data.frame(x, y, data = as.factor("data1"))
  
  y &lt;- c()
  for (i in 1:length(x)) {
    y &lt;- c(y, runif(1, min = length(x) - i, max = length(x)))
  }
  
  my.data.frame2  &lt;- data.frame(x, y, data = as.factor("data2"))
  
  merged &lt;- rbind(my.data.frame1, my.data.frame2)
  
  ggplot(merged, aes(x, y, color = data)) + geom_point() + geom_line()
  </code></pre>
  
  <p>So for each type of data (data1 and data2), and for each date value on the x axis, I have 3 y values.</p>
  
  <p>The plot looks (bad) like this:</p>
  
  <p><a href="https://i.stack.imgur.com/UWRut.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UWRut.png" alt="enter image description here"></a></p>
  
  <p>What I want to do is to plot a <code>geom_ribbon</code> of the data but I don't know how to do it.</p>
  
  <p>I first tried to extract the min and max values with an <code>aggregate</code> function as explained <a href="https://stackoverflow.com/questions/25314336/how-to-extract-the-maximum-value-within-each-group-in-a-data-frame">here</a> for each time and build a new data frame without duplicate x values but couldn't make it work.</p>
  
  <p>Can anyone help?</p>
  
  <p><strong>Edit:</strong></p>
  
  <p>The code I tried with <code>aggregate</code> is this one:</p>
  
  <pre><code>aggregate(y ~ x, data = merged, max)
  </code></pre>
  
  <p>(Same for the min). But this does not make the difference between the data1 set and the data2 set. I know I could subset, but I guess it can be done using the "by" argument. Just couldn't make it work.</p>