1

I am trying to create lattice xyplot with multiple panels using the code below. The problem is that it is adding all median lines on all panels (i.e ablines are not grouped by Subject). Is there a way to subset median lines per subject?

Below is a reproducible example using Theoph dataset from PKPDdatasets package.

# devtools::install_github("dpastoor/PKPDdatasets")
library(PKPDdatasets)
library(lattice)
library(latticeExtra)
library(dplyr)

Theoph_Data <- Theoph

Theoph_Data1 <- Theoph_Data %>% group_by(Subject) %>% mutate(Median= median(Time))

print(Theoph_Data1)

Theoph_PK <- xyplot(conc ~ Time| Subject, data=Theoph_Data1,
                   panel = function(x,y,...) {
                   panel.xyplot(x,y,...)
                   panel.abline(v=Theoph_Data1$Median)
                   })
Theoph_PK
MrFlick
  • 195,160
  • 17
  • 277
  • 295
Krina M
  • 135
  • 2
  • 13
  • 1
    Welcome to stack overflow! Please try to [make this question reproducible](http://www.stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). You are much more likely to get a quality answer. – shayaa Aug 06 '16 at 22:23
  • Thank you, Shayaa. I just updated my question with example. Will greatly appreciate your help. – Krina M Aug 06 '16 at 23:20
  • Was able to solve it as per answer below: http://stackoverflow.com/questions/21175945/adding-different-vertical-lines-for-each-panel-in-xyplot-using-lattice-in-r – Krina M Aug 07 '16 at 00:11
  • Theoph_Data1$Median consists of a single value. – shayaa Aug 07 '16 at 00:13

1 Answers1

0

While your example isn't the best because every individual has the same median time, the basic idea is this:

Theoph_Data <- Theoph
xyplot(conc ~ Time| Subject, data=Theoph_Data1,
    panel = function(x,y,subscripts,...) {
        panel.xyplot(x,y, subscripts=subscripts,...)
        panel.abline(v=median(Theoph_Data1$Time[subscripts]))
    }
)

You can request the subscripts= parameter in your panel function. This will give you the indexes for the observations plotted in each panel. You can then subset the original data using those subscripts. Here we calculate the median right in the function (to make sure we only try plotting a single line with a single value).

enter image description here

MrFlick
  • 195,160
  • 17
  • 277
  • 295