Announcement

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

  • Use subinstr and macro when creating new names in a foreach

    Hello, I am doing a lot of -foreach- statements, giving a variable a new name. An example:

    Code:
     foreach x of varlist $nominal {
    capture gen real_`x' = `x'*deflator
    Next I want to create an average by year, instead of having avg_real_"name", i would like to have only avg_"name", so I use the real values to do the calculations, but I want to have the nominal names with an avg_ prefix. I tried to do something like this:

    Code:
    foreach x of varlist $real {
    capture by year: egen subinstr(`x',$string,"avg",1) = mean(`x')
    }
    But this gives an error, invalid syntax.

    In $string I have "wage asset ...", after I ran the code I figured out that was obviously going to fail. Does anyone have a pointer or a hint to something that would do this? The goal is to create shorter/snipped names without much extra/manual work.

  • #2
    I guess that your loop should be more like

    Code:
    foreach x of global real {
        local X : subinstr local x "real" "", all
        capture by year: egen avg_`X'  = mean(`x')
    }
    Let's identify the confusions:

    1. You can use the subinstr() function on the fly but the form above using equivalent syntax is easier when you're learning.

    2. The second argument of subinstr() should in this case be a literal string in "". A single variable name would be legal but otherwise Stata doesn't know what you want.


    Last edited by Nick Cox; 30 Jul 2018, 05:45.

    Comment


    • #3
      That looks exactly what I am looking for, I see that you are doing. I am quite inexperienced with string functions, so this helped alot. I gave it a try and it works like a charm! (One small problem was that "_" is included twice, which is of course solved by removing "_" from old variable or not including it in the new of course )

      Comment


      • #4
        Indeed. Glad it helped.

        Comment

        Working...
        X