I have a variable ranking
which consists of many groups of different sizes which are all ranked. So one group might be 1-6 the next 1-4 and the next 1-52.
I know want to create two variables that sum the differences between an individual and all individuals above and below him respectively.
For a group of 5 individuals and individual 1 that means I want to get
UP: SUM(1-1) =0
DOWN: SUM((1-5)+ (1-4)+ (1-3)+ (1-2)) = -10
Some considerable guesswork seems needed here. Summing the differences in ranks seems unlikely to be what you want, as those are just a couple of arithmetic progressions which are not informative about the data.
The following is reproducible and may help.
. sysuse auto, clear
. bysort rep78 (mpg) : gen rank = _n
. bysort rep78 (rank) : gen cuscore = sum(mpg)
. bysort rep78 (rank) : gen above = cuscore - mpg
. bysort rep78 (rank) : gen below = cuscore[_N] - cuscore
Thanks Nick,
this was actually very helpful.
I made small modifications to get what I want and checked that it worked in the data window.
I am sorry for not phrasing my question too well and not providing a toy example.
Here is my modified answer with comments should anyone in the future come by this post
sysuse auto, clear
*just to have a better overview in the data window
keep mpg rep78
*creates ranking first by rep78 and within that by mpg
bysort rep78 (mpg) : gen rank = _n
*Sums mpg by rep78 and then by rank
bysort rep78 (rank) : gen cuscore = sum(rank)
*Create up as sum of the ranks minus individual rank
bysort rep78 (rank) : gen up= cuscore - rank
bysort rep78 (rank) : gen down= cuscore[_N] - cuscore