I'm reading the documentation for margins, and in particular "Example 9: Decomposing margins".

In there we have the model:
Code:
logistic outcome i.sex i.group sex#group age
and we compute the margins for males and females with:
Code:
margins sex
We then decompose the margins as follows:
1. The margin for males, 0.160, treats everyone as if they were male, and that amounts to
simultaneously:
1a. treating males as males and
1b. treating females as males.

2. The margin for females, 0.197, treats everyone as if they were female, and that amounts to
simultaneously:
2a. treating males as females and
2b. treating females as females.
We obtain 1a and 2a with:
Code:
margins if sex==0, at(sex=(0 1))
While we obtain 1b and 2b with:
Code:
margins if sex==1, at(sex=(0 1))
We obtain the following decomposition (I added numbers):
T) Margin treating everybody as themself: 0.170

A) Margin treating everybody as male: 0.160
A.1) Margin treating male as male: 0.079
A.2) Margin treating female as male: 0.240

B) Margin treating everybody as female: 0.197
B.1) Margin treating male as female: 0.134
B.2) Margin treating female as female: 0.260
I wonder: what is the relationship between those numbers?

From my "experiments", it looks like B is a weighted average of B.1 and B.2. A is a weighted average between A.1 and A.2. But the total margin T is NOT a weighted average between A and B.

Why is that?

Here is my code:
Code:
logistic outcome i.sex i.group sex#group age

margins
scalar margin_total = r(b)["r1","_cons"]

margins sex
scalar margin_male = r(b)["r1","0.sex"]
scalar margin_female = r(b)["r1","1.sex"]

// get 1a and 2a
margins if sex==0, at(sex=(0 1))
scalar margin_subm_male = r(b)["r1","1._at"]
scalar margin_subm_female = r(b)["r1","2._at"]

// get 1b and 2b
margins if sex==1, at(sex=(0 1))
scalar margin_subf_male = r(b)["r1","1._at"]
scalar margin_subf_female = r(b)["r1","2._at"]

quietly sum sex
scalar pfemale=r(mean)

// wrong
disp margin_total
disp pfemale*margin_female + (1-pfemale)*margin_male

// ok
disp margin_male
disp pfemale*margin_subf_male + (1-pfemale)*margin_subm_male

// ok
disp margin_female
disp pfemale*margin_subf_female + (1-pfemale)*margin_subm_female