Announcement

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

  • forvalue loop for discontinuous variable

    How I can use a forvalue loop over the variable whose values are not sequentially continuous? I want to use forvalue loop for the industry codes which are not continuous and huge in numbers.

  • #2
    You could do it by creating a new variable that sequentially indexes its values with -egen, group()-. But why would you want to do that? Better is to use a -foreach- loop over its values:
    Code:
    levelsof industry_code_variable, local(codes)
    foreach c of local codes {
        whatever
    }
    Last edited by Clyde Schechter; 27 Jan 2023, 15:54.

    Comment


    • #3
      Clyde explained two of the approaches, the one he prefers with -levelsof- is more elegant, but might fail if you have too many levels. The most general strategy is to map to a sequential variable using -egen, group()-.

      There is also a third approach which I have not seen being used much, probably because it is neither elegant, nor faster (according to my own experiments): you can just go through the minimum and the maximum value, and write the code in the whatever such that it does not break if there is no industry with the given number.

      Comment


      • #4
        The FAQ https://www.stata.com/support/faqs/d...-with-foreach/ discusses all the solutions so far mentioned.

        Comment

        Working...
        X