I wonder whether there is a function/tool/package that will generate a **contrast matrix** from a **model-matrix** or a **formula**, without manually specifying the compared groups.

For example, assuming 3 groups *A, B, C* and given a formula such as ** ~0 + Group + Age + Sex** and/or its generated

`model.matrix()`

, I'm looking for a way to generate a **contrast matrix**such as

GroupAvsB | GroupAvsC | GroupBvsC | |
---|---|---|---|

GroupA | 1 | 1 | 0 |

GroupB | -1 | 0 | 1 |

GroupC | 0 | -1 | -1 |

Age | 0 | 0 | 0 |

Sex | 0 | 0 | 0 |

This can be even more complicated if a formula has interacting terms such as `~ 0 + Group*Sex + Age`

, or when there is a substantial number of groups.

The CRAN package `emmeans`

is doing a similar parsing of a model:

```
pigs.lm <- lm(log(conc) ~ source + factor(percent), data = pigs)
pairwise.table <- emmeans(pigs.lm, pairwise ~ source)[[2]]
coef(pairwise.table) %>% magrittr::set_colnames(c(colnames(.)[1], summary(pairwise.table)$contrast))
#> source fish - soy fish - skim soy - skim
#> fish fish 1 1 0
#> soy soy -1 0 1
#> skim skim 0 -1 -1
```