Stata:Comparison within a variable but between individuals

▼魔方 西西 提交于 2019-12-25 18:02:23

问题


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


回答1:


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



回答2:


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 


来源:https://stackoverflow.com/questions/17576316/statacomparison-within-a-variable-but-between-individuals

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!