Announcement

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

  • indexing in forvalues

    I have a dataset with a set of variables labeled t0_X t1_X ... t12_X
    I want to perform a set of operations on t*_X using both the current index number of t*_X and the previous index number (t-1)*_X.
    I have a forvalues command as follows:
    forvalues i=1(1) 12 {
    gen t`i'_Y=t`i"_X-t`z'_X where `z'==`i'-1.

    However this doesn't work. I tried a number of options but couldn't get this to work (for example I tried a "forvalues z=`i'-1 (1) 11 { " which gave me an error message.

    Any help would be appreciated.
    Zeev

  • #2
    Something like this?

    Code:
    forvalues i=1(1)12 {
        local z = `i' - 1
        di "t`i'_X - t`z'_X"
        * gen t`i'_Y = t`i'_X - t`z'_X
    }
    Although, it kind of seems like you have time-ordered data in wide format. If so, this would be easier if the data were in long format. See:

    Code:
    help reshape
    Last edited by Daniel Schaefer; 12 Jun 2023, 13:45.

    Comment


    • #3
      Thanks that seems to work. However, reshaping the data would be complex because it is a very large file and some of the variables are constant across a group of time points.

      Comment


      • #4
        Of course you are free to ignore my advice if you like. However, the long format is generally much preferred in Stata, which has powerful syntax for dealing with the data in long format. This syntax would, among other things, allow you to solve this particular problem in a single, simple line of code. Time-invariant variables aren't a problem, and while it may take a bit of processor time to execute, you should save a great deal of programer time in the long run by taking advantage of Stata's built-in time series features.

        Comment


        • #5
          reshaping the data would be complex because it is a very large file
          If what you are concerned about here is the amount of time it would take, there are user-written commands -tolong- and -greshape- that are much faster than Stata's native -reshape long- command in large data sets. -greshape- is part of the -gtools- suite. Both -tolong- and -gtools- are available from SSC. And there is no real learning curve to use them because both of them will accept the same syntax as Stata's -reshape- command.

          Comment

          Working...
          X