Announcement

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

  • Making n new variables by doing rolling difference of existing variables

    Hi statalist colleagues,

    I was struggling with a quite simple thing I guess.

    Code:
    foreach v of varlist YSVR9909ASREPGDP - YSVR2105ASREPGDP {
        replace temp_`v' = `v' - `v-1'
        tab temp_`v'
    }
    What I am trying to create is a variable where I take the difference between the two variables in the variable list.


    So if there is var1 var2 var3

    I am trying to create

    temp_var2 = var2-var1
    temp_var3 = var3-var2

    I couldn't figure this out, as pointing to a previous column was not doable with [_n-1] or L. which are only used for rows(i.e. observations).

    It would be great if someone could share their knowledge on this.

    Thanks much,

    Ed

  • #2
    Code:
    ds YSVR9909ASREPGDP-YSVR2105ASREPGDP
    forval x = 2/`:word count `r(varlist)''{
        gen temp_`:word `x' of `r(varlist)'' = `:word `x' of `r(varlist)'' - `:word `=`x'-1' of `r(varlist)''
    }

    Comment


    • #3
      Hi Ali Atia , thank you so much for your response.
      It seems to work with the codes. Just for learning purpose, may I please ask what this 2nd line means?
      Code:
       forval x = 2/`:word count `r(varlist)'
      I tried to dig out the logic here but couldn't understand it. Thank you so much Ed

      Comment


      • #4
        The `:' syntax allows you to evaluate a macro function on the fly. The word count macro function counts the amount of variables in the list YSVR9909ASREPGDP-YSVR2105ASREPGDP and sets that as the maximum value for the loop.

        So all told that line substitutes to forval x = 2/3. If there were four variables it would substitute to forval x = 2/4, etc.

        Comment


        • #5
          Hi Ali,

          thank you so much for the explanation. It is very clear now.

          Many thanks,
          Ed

          Comment


          • #6
            All that said, this gives the impression that panel data is being stored in wide layout. If so, many problems will require this kind of loop. It would usually be better to reshape long.

            Comment

            Working...
            X