My suggestion is to declare the storage immediately before the loop like so:
b_storage = j(c_rows, 2, .);
That is a matrix with as many rows as combinations, 2 columns and filled with missing values. Once you have the matrix b in the loop, then copy it to the ith row of the storage matrix as follows:
b_storage[i, ] = b;
The if/then/else statement can then be deleted, as can the definition of matrix b_storage_first.
Incidentally the statements that define group_col and lag2cvrank_col can be moved outside of the loop, they are being overwritten on every iteration of the loop - this will save a bit more time.
Finally, have you thought what happens if you have two data rows with identical pairs of x-values?
... View more