Solution (source code)

= Solution

There is an apparent reversal, but not a mathematical contradiction. The crude <odds ratio> averages over the actual background distribution in each group, whereas the adjusted <logistic regression> compares groups at the same fitted background values. Strong <confounding> could make those distributions very different: for example, elective patients might disproportionately come from low-risk backgrounds or clinics, while the reference patients come from higher-risk backgrounds. The <Simpson paradox> can then reverse the marginal comparison even when every conditional comparison favours the same direction.

The <noncollapsibility of the odds ratio> can also make marginal and conditional odds ratios differ in magnitude. It does not, by itself, explain a sign reversal if both groups have the same covariate distribution and the common conditional effect has one sign: if $p(1,x)>p(0,x)$ for every $x$, averaging over the same distribution of $x$ still gives a larger exposed risk. A genuine reversal therefore requires differing background distributions, heterogeneous effects or another change in what is being compared. The observed reversal is a reason to investigate these issues, not proof of a programming error.