# calculating selected contrasts with emmeans within treatment

I have a dataset that has data collected at 8 different timepoints and in 5 different treatment groups, and want to do multiple pairwise comparisons. However, I want to run comparisons only between treatments within timepoints (66 comparisons) and between timepoints within treatments (99 comparisons), since for example the comparison of treatment 1, timepoint 1 with treatment 2, timepoint 5, makes no sense and should not be corrected for (396 comparisons). I used model.int <- lmerTest::lmer (y ~ treatment : timepoint + (1 | ID)) to run the mixed effect model, model.emm <- emmeans::emmeans(model.int, 'timepoint') to calculate estimated marginal means (aka least-squares means) based on this model, and pairwise.model.emm <- emmeans::contrast(model.emm, method = 'pairwise') for the pairwise comparisons. Within this approach, I tried both the by and the simple option, but they do not result in what I need.

I would do:

EMM <- emmeans(model.int, ~ treatment * timepoint, nesting = NULL)
pairs(EMM, simple = "each")


Note that the emmeans() call needs to specify both factors.

That said, I must misunderstand something because if there are 8 time points and 5 treatments, then there are $$8 \times {5\choose2} = 8 \times 10 = 80$$ pairwise comparisons of 5 treatments at each of 8 time points -- not 66 as stated. Similarly, there are $$5 \times {8\choose2} = 5\times28 = 140$$ (not 99) pairwise comparisons of 8 time points with each of 5 treatments. Finally, there are $${40\choose2}=780$$ (not 396) pairwise comparisons of the 40 factor combinations.

I added nesting = NULL to force bypassing the grouping imposed by the detection of nests in the empty-cells structure.
• Thanks for the suggestion, but this gives me the following error message: NOTE: A nesting structure was detected in the fitted model: treatment%in% (treatment*timepoint), timepoint%in% (treatment*timepoint) And by the way, you are right about the number of pairwise comparisons, but my dataset does not havve all parameters taken at every timepoint, and some specific measurments could not be taken on one of the timpoint in one of the groups. This reduced the actual number of comparisons. Commented Apr 19, 2021 at 5:39
• That's actually not an error message, it is just a message. Clearly, you have a lot of holes in the data, because that's the explanation of the message. You can add nesting = NULL to the emmeans call.You'll get a lot of non-estimable comparisons, but you're expecting them. Commented Apr 19, 2021 at 13:00
• Great. I wonder also if the nesting thing would have been averted if your model formula in the lmercall had used * instead of :. That is, your model excludes the main effects of both factors and that's why it thinks the factors are nested. Commented Apr 21, 2021 at 12:50