Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Creating a loop to replace value x if value y is among 20 variables

    Hi,

    Im quite new to Stata, but get by with using the manual and this forum. I´ll try to explain my problem as precise as possible and apologise in advance if I'm using the wrong terms.

    I have a dataset of 4.000.000 on patients hospitalised with viral infections. One complication during hospitalisation is an arterial thromboembolism, and I'm trying to make the variable ATE_type with values 1-8 for the different types based on the discharge diagnosis code (diagnosis_1_1......diagnosis_20_1) which is in string format.

    At first I used the following code:

    gen ATE_type=.
    replace ATE_type=1 if diagnosis_1_1=="I740"

    Its simple, but to copy/retype the code 8 times for all 20 diagnosis variables is too inefficient. I've tried reading the manual and this forum, but don't understand how to make a loop that can replace the ATE_type value if a certain code e.g. "I740" is found in any of the 20 diagnosis code variables.

    Can anyone help me?

    Thanks in advance!

  • #2
    I believe this will get you almost what you want,
    Code:
    gen ATE_type=.
    foreval i = 0/9 {
    foreach v of var diagnosis* {
    replace ATE_type = `i' if `v' == "I74`i'"
    }
    }
    Last edited by Øyvind Snilsberg; 16 Feb 2022, 10:39.

    Comment


    • #3
      Thank you so much! That worked perfectly!

      Comment

      Working...
      X