0

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.

2
  • Is this really reverse sorting, or is it a matter of giving pairs of observations the other observation's values? See stata-journal.com/article.html?article=dm0043 Commented Feb 19, 2021 at 17:12
  • Thank you for your answer Nick. I believe that this document applies to the cases when we already have another variable that defines the pairing i.e. VarC in this case. However, I don't have the varC and I want to create it based on varB. Commented Feb 21, 2021 at 18:49

1 Answer 1

1

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      .        . |
     +----------------------------------+
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.