Announcement

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

  • Loop over unique values of variable

    Info:
    Win 7 - 64bit
    Stata 12.1 SE
    12GB RAM / i5 - maschine

    Dear All,

    I have a set 245.000 loans I want to calculate IRRs for.
    I set it all up pretty lean:

    use ".\dta\xxx.dta"
    keep id survivaltime_m id funded_amnt int_rate installment
    gen a0 = -1*funded_amnt
    local i
    forvalues i =1(1)60{
    gen a`i'=0
    replace a`i'=installment if `i'<= survivaltime_m
    }
    reshape long a, i(id) j(time)
    tsset id time

    So far it is fine. Now I am trying to loop over all the IDs of the
    loans to calculate the IRR.

    gen save = 0
    local i
    foreach i in `id' {
    finirr a if id == `i'
    replace save = r(irr) if id == `i'
    }

    This simply does not work. The Loop runs without any error message.
    However, no results are saved in save.

    I did my homework and tried several alternatives:

    levelsof id, local(ids)
    foreach i of local ids {
    finirr a if id == `i'
    replace save = r(irr) if id == `i'
    }


    egen group = group(id)
    su group, meanonly
    foreach i of num 1/2{
    finirr a if id == `i'
    replace save = r(irr) if id == `i'
    }

    NOTHING works ! :-(

    Any help would be warmly appreciated !

  • #2
    You need to combine your first two attempts. Try this:

    Code:
    levelsof id, local(ids)
    foreach i in `ids' {
    finirr a if id == `i'
    replace save = r(irr) if id == `i'
    }
    Your use of foreach i of local ids is actually looping through a list of local macros (only one in this case) rather than looping through the elements contained in a local macro. Your first attempt involved looping through the elements of a macro (`id') that doesn't exist.

    Comment


    • #3
      Apparently, I am mistaken: foreach i of local ids should actually work. (I didn't have access to Stata to check this when I posted previously.) Accordingly, the only thing I can suggest is to do a set trace on before your code and see what is actually in the macro `i' at the time the finirr command is run. Since the finirr command is a user-written command (something you should have mentioned when you first posted), the problem may be there, rather than with your macro. In any case, the trace output should help narrow down where the problem is.

      Comment


      • #4
        Joe put his finger on a key detail. finirr is user-written, that user being Vince Wiggins. It's the OP's job to explain that.

        But as the help explains finirr is byable, so you may not need a loop at all. In fact, I guess wildly that finirr was all along written with a panel context in mind.

        Comment

        Working...
        X