Announcement

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

  • loop variables with * wildcard

    I have a list of variables that I want to loop through:

    yr2008_q110atte
    yr2009_q112atte
    yr2010_q112atte
    yr2011_q110atte
    yr2012_q110atte

    As you can see, they all start with "yr" and ends with "atte", although the question number in each year is different.

    So, I write the loop below:

    foreach i in 2008 2009 2010 2011 2012{
    tab yr`i'_*atte yr`i'_age_grp
    gen yr`i'_atte = . if yr`i'*atte == 1
    gen yr`i'_atte = 1 if yr`i'*atte == 1
    replace yr`i'_atte = 0 if yr`i'*atte == 1
    }

    The first line of tabulating variables works, but starting from the second line within the loop, the yr`i'*atte condition doesn't work, as stata returns "yr2008 ambiguous abbreviation".

    Any clue on how to resolve this? Thank you!

  • #2
    I would take a slightly different approach here. It seems that each year has a single yr*_atte variable associaed with it, and you want to tabulate that variable against the corresponding year's yr*_age_grp. So far so good. Then you want to create some variable whose name is yrX_atte, where X is replaced with the year of the variable in the current loop iteration. But you have three lines of code that make no sense to me in connection with that. All three of those commands will throw syntax errors because of the -if yr`i'*atte == 1- part. I presume that you mean you want to do this if the current loop iteration variable is 1. But then the second line attempts to -gen- the same variable again: which you can't do once it exists. Finally you want to -replace- that result with 0. So I don't understand why you don't just have a single command that sets that variable to 0 in the first place. Anyway, I can't make any sense of what you're trying to do with those three commands. So I will leave you with this approach:

    Code:
    ds yr*atte
    local vlist `r(varlist)'
    foreach v of varlist `vlist' {
        local year = substr("`v'", 3, 4)
        tab `v' yr`year'_age_grp
        gen yr`year'_atte = ???? if `v' == 1
    }
    Anyway, replace ???? with something that does what you want there.

    Comment

    Working...
    X