Announcement

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

  • Looping over two variables at once

    Hi !
    I have been using STATA not for so long. And now I'm trying to loop over 2 variables at the same time in order to generate a new variable. My data, as shown in the attached dta file looks like lpermno trt1m (which is the monthly stock returns) year mydatemonthly rf.
    The question is that, for every lpermno, I want to generate monthly excess returns=trt1m/100-rf.
    I tried doing the following but it's not working:

    egen group = group( lpermno mydatemonthly)
    su group, meanonly
    foreach i of num 1/`r(max)' {
    gen ret= trt1m- rf if group == `i'
    } //invalid numlist has too many elements

    Then, I tried this but in vain:
    egen group1 = group(mydatemonthly)
    su group1, meanonly
    local maxrf = r(max)

    egen group2 = group( lpermno)
    su group2, meanonly
    local maxlpermno = r(max)

    foreach i of num 1/`maxlpermno' {
    foreach t of num 1/`maxrf' {
    gen ret= trt1m/100- rf if group1 == `i' & group2 == `t'
    }
    }

    Any suggestions are welcome !
    Attached Files

  • #2
    Salma --

    When I try and run your code, I run into one obvious problem: you are trying to generate the variable ret each time through the loop. So, the question is if you intend to generate only one variable, ret, in which case, you should do something like:
    Code:
    egen group = group( lpermno mydatemonthly)
    su group, meanonly
    gen ret=.
    foreach i of num 1/`r(max)' {
    replace ret= trt1m- rf if group == `i'
    }
    Or if you want a separate variable for each, you don't have to pregenerate the variable. You would just do:
    Code:
    egen group = group( lpermno mydatemonthly)
    su group, meanonly
    foreach i of num 1/`r(max)' {
    gen ret`i'= trt1m- rf if group == `i'
    }
    I don't know if that's the whole problem, but I hope that helps.

    Matt Baker

    Comment


    • #3
      Matthew
      That works. Thank you very much.

      Comment


      • #4
        As a side note, this is general Stata question, not a Mata question. In the future you'll likely get more readers for your question if you ask questions in the general forum.
        (Unless, of course, your question really is about Mata programming)

        Comment


        • #5
          There's nothing in your inquiry that requires looping or grouping. Stata will perform the same operation on all observations at the same time. All you need is

          Code:
          gen ret = trt1m / 100 - rf

          Comment


          • #6
            Robert !
            That's right. I tried it and it just generated the same values, so you're right, it's as simple as that! Thanks!

            Comment

            Working...
            X