Announcement

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

  • Creating a loop to run a command when the suffixes match

    I have the following code in Stata 17 that aims to run a command when the suffixes match. In other words, use days_a with freq_a, days_b with freq_b, and so on. However, it still gives me all combinations from valist 1 and varlist 2. Do you know what is wrong with my code? Thank you!


    foreach var1 of varlist days_a days_b days_c days_d days_e days_f days_g days_h days_i days_j {
    local var1suffix substr("`var1'", strpos("`var1'", "_")+1, length("`var1'"))
    foreach var2 of varlist freq_a freq_b freq_c freq_d freq_e freq_f freq_g freq_h freq_i freq_j {
    local var2suffix substr("`var2'", strpos("`var2'", "_")+1, length("`var2'"))
    if "`var1suffix'" == "`var2suffix'" & "`var1suffix'" != "" {
    total(`var1'), over(`var2')
    }
    }
    }

  • #2
    This is way more complicated than you need. You just need a single loop over the first ten letters of the alphabet:
    Code:
    foreach x in a b c d e f g h i j {
        total days_`x', over(freq_`x')
    }
    That said, in case you ever need to actually do two nested loops and restrict the inner code to situations where some aspects of the two iterators match, here's how your code can be fixed to perform in the way you hoped for:
    Code:
    foreach var1 of varlist days_a days_b days_c days_d days_e days_f days_g days_h days_i days_j {
        local var1suffix = substr("`var1'", strpos("`var1'", "_")+1, length("`var1'"))
            foreach var2 of varlist freq_a freq_b freq_c freq_d freq_e freq_f freq_g freq_h freq_i freq_j {
            local var2suffix = substr("`var2'", strpos("`var2'", "_")+1, length("`var2'"))
            if "`var1suffix'" == "`var2suffix'" & "`var1suffix'" != "" {
                total(`var1'), over(`var2')
            }
        }
    }
    When you code -local mylocal some_expression- the value of local macro mylocal will be set to `"some_expression."' But that is not what you wanted. You did not want to set var1suffix to be `"substr("`var1'", strpos("`var1'", "_")+1, length("`var1'"))"'. You wanted Stata to evaluate substr("`var1'", strpos("`var1'", "_")+1, length("`var1'")) and then store the result of that evaluation (the suffix itself) into local macro var1suffix. To do that, you have to use the = operator in the command defining the local macro.

    Comment


    • #3
      Thank you so much!! I actually replaced the letters for other variables names that I didn't post on purpose but your code definitively fixed my problem. I appreciate you explaining what the problem was with the macro my local. This is very useful for the future!

      Comment

      Working...
      X