adamsalenushka
adamsalenushka

Reputation: 49

Stata: Reverse Sort

I have a data set that looks like this:

id varA  varB   varC
1   0     10    .
1   0     20    .
1   0     35    .
2   1     60    76
2   1     76    60 
2   0     32    .
         

I want to create the varC that reverses the order of varB only for the values varA=1 and missing otherwise.

Upvotes: 0

Views: 324

Answers (1)

Nick Cox
Nick Cox

Reputation: 37208

This may help:

clear 
input id varA  varB   varC
1   0     10    .
1   0     20    .
1   0     35    .
2   1     60    76
2   1     76    60 
2   0     32    .
end 

gen group = sum(id != id[_n-1] | varA != varA[_n-1])
sort group, stable 
by group: gen wanted = cond(varA == 1, varB[_N - _n + 1], .)

list id var* wanted, sepby(id varA) 

     +----------------------------------+
     | id   varA   varB   varC   wanted |
     |----------------------------------|
  1. |  1      0     10      .        . |
  2. |  1      0     20      .        . |
  3. |  1      0     35      .        . |
     |----------------------------------|
  4. |  2      1     60     76       76 |
  5. |  2      1     76     60       60 |
     |----------------------------------|
  6. |  2      0     32      .        . |
     +----------------------------------+

Upvotes: 1

Related Questions