Announcement

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

  • Foreach loop with part of variable name

    Hi Statalist. I'm having a bit of trouble finding the help file that will let me achieve something particular with a foreach loop.

    I have several variables in pairs. e.g a_com and a_firm, b_com and b_firm, c_com and c_firm, etc. I want to create new variables for the difference between each. Once I've got the difference variable, it's easy to use a "foreach var" command to manipulate them. However, I can't work out how to use a loop to take the differences. I think the code I need is something like:

    foreach i in a b c etc {
    gen `i'_dif = `i'_firm - `i'_com
    {

    But it's not quite working. Can anyone help me out?

    Thanks,
    Arthur

  • #2
    Hi Arthur. Try the following:
    Code:
    local letters a b c
    foreach i of local letters {
      gen `i'_dif=`i'_firm - ì'_com
    }

    Comment


    • #3
      Alberto's code accidentally turned a `i' into an accented i. This is what he intended
      Code:
      local letters a b c
      foreach i of local letters {
        gen `i'_dif=`i'_firm - `i'_com
      }
      With that said, I suggest you review the Statalist FAQ linked to from the top of the page, as well as from the Advice on Posting link on the page you used to create your post. Note especially sections 9-12 on how to best pose your question.

      The more you help others understand your problem, the more likely others are to be able to help you solve your problem.

      Section 12.1 is particularly pertinent

      12.1 What to say about your commands and your problem

      Say exactly what you typed and exactly what Stata typed (or did) in response. N.B. exactly!
      ...
      Never say just that something "doesn't work" or "didn't work", but explain precisely in what sense you didn't get what you wanted.
      as is Section 12.3 on the use of code delimiters to present code and output from the results window.

      Comment


      • #4
        Arthur got very good advice. Ironically, or otherwise, the code shown in #1 looks fine apart from "etc." which presumably was not in the original and the wrong brace (curly bracket).

        Code:
        foreach i in a b c {
              gen `i'_dif = `i'_firm - `i'_com
        }

        Comment

        Working...
        X