Adding up inside the city before squaring keeps the pairs that share a city
The loop's one important move is the order: add, then square.
Predict
City A's residuals are -5, -2, -4 and -1. Their total squared is 144, and the diagonal, each user alone, adds up to 46. What do the other 12 cells hold?
×
-5
-2
-4
-1
-5
25
10
20
5
-2
10
4
8
2
-4
20
8
16
4
-1
5
2
4
1
City A
Adds up to
the diagonal, each user alone
25 + 4 + 16 + 1 = 46
the whole grid, the total squared
(-12) × (-12) = 144
the other 12 cells, the pairs in A
144 - 46 = 98
City A is from the six cities. Its users' values are 1, 4, 2 and 5, and the control arm's mean is 6, so its residuals are -5, -2, -4 and -1.
Square a sum and you get every product of two of its terms. The diagonal is what you'd get by squaring each user alone. The other 12 cells are the pairs of users who share city A. They're all positive because A's users all sit below their arm's mean together.
That's the whole trick, and the order is what matters. Add up inside the city, then square. Squaring the sum keeps every cross-product e^ie^j between two users of the same city. That's exactly the within-city correlation the naive formula throws away.
Pairs from different cities never meet:
A sketch, 3 cities of 2 users: the pairs each estimator adds up
naive and robust: each user alone
clustered: every pair inside one city
Rows and columns are users, in city order. The clustered estimator adds up every marked cell.
Each grid has one row and one column per user. A ■ is a pair whose product enters the estimate. Each 2 by 2 block on the clustered grid's diagonal is one city, like city A's 4 by 4 grid above, only smaller. The cells outside the blocks, pairs from different cities, are left out, because different cities are assumed independent.
In the editor, write sum_then_square(cities) and square_then_sum(cities): the two ways to add up residuals.
Pick an answer above to see the rest
Instructions
1
Write sum_then_square(cities): each city's residuals added up, then squared, then added over cities.
2
Then write square_then_sum(cities): every residual squared, then added. cities is a list of each city's residuals.