title: Lattice Plot - Add lines through mean of y values
body: <p>I want to print a <code>lattice::xyplot</code> with grouped points and lines, but I have multiple <code>y</code> values for many of the individual <code>x</code> values in each group.  I want a segmented line printed, so that for each <code>x</code> value, it passes through the mean of the relevant <code>y</code> values in each group.</p>
  
  <p>Here's an example:</p>
  
  <p>Using this data:</p>
  
  <pre><code>set.seed(1)
  d &lt;- data.frame(x=sample(6, 20, replace=TRUE), y=rnorm(20), g=factor(sample(2, 20, replace=TRUE)))
  # Shift one group
  d$y[d$g==2] = d$y[d$g==2] + 5
  </code></pre>
  
  <p>I've shifted one group so the lines are more visually appealing.</p>
  
  <p>A scatter plot looks like this:</p>
  
  <pre><code>xyplot(y ~ x, data=d, groups=g)
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/VhnSL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/VhnSL.png" alt="enter image description here"></a></p>
  
  <p>Just adding lines is a real mess:</p>
  
  <pre><code>xyplot(y ~ x, data=d, groups=g, type=c('p','l'))
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/G4mOI.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/G4mOI.png" alt="enter image description here"></a></p>
  
  <p>It's a bit better if you sort the <code>x</code> values, but still not what I want:</p>
  
  <pre><code>xyplot(y ~ x, data=d[order(d$x),], groups=g, type=c('p','l'))
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/a7MPR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/a7MPR.png" alt="enter image description here"></a></p>