Announcement

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

  • Creating a loop to generate a new variables in a panel dataset

    I would be be grateful for any help with my query.

    I have the following variables chd002_9 chd002_09 sti002_9 sti002_09 pad002_9 pad002_09…….
    I have about 40 variables which I would like to use to generate new variables.

    For each variable with the same prefix (1st 3 letters) I want to do the following:

    1. I want to generate a new variable which uses the 1st three letters of the original variable and add “_qof” at the end for example: chd_qof pad_qof sti_qof
    2. Variables ending in _9 correspond to years 2013 & 2014 while those ending in _09 correspond to years 2015 &2016
    3. For variables ending in _09 I want to multiply by 100

    If I were doing each variable in turn, the code would look like this:

    gen chd_qof = .
    replace chd_qof = chd002_9 if year ==2013
    replace chd_qof = chd002_9 if year ==2014
    replace chd_qof = chd002_09 *100 if year ==2015
    replace chd_qof = chd002_09*100 if year ==2016

    Although, I have some experience with loops, I have no idea where to start with this one. Any help would be greatly appreciated.

  • #2
    I see no data example here, but your code seems to reduce to

    Code:
    gen chd_gof = cond(year <= 2014, chd002_9, 100 * chd002_9)
    which suggests that a loop could look like

    Code:
    foreach pre in chd sti pad { 
        gen `pre'_gof = cond(year <= 2014, `pre'002_9, 100 * `pre'002_9)
    }
    There might be better ways to clean up your data unless this is the main part of doing that.

    For more on cond() see https://www.stata-journal.com/sjpdf....iclenum=pr0016

    Comment


    • #3
      Dear Nick, Thank you much for your assistance and for directing me to the use of cond(). I made one small tweak to your suggested code which now works perfectly.

      Code:
      foreach pre in chd pad {
      gen `pre'_qof = cond(year <= 2014, `pre'002_9, 100 * `pre'002_09)
      }

      Comment


      • #4
        Good catch.

        Comment

        Working...
        X