Announcement

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

  • Using forvalues command

    Hello,

    I'm reasonably familiar with the 'forvalues' command, however I'd like to do something like this:

    Code:
    forvalues y=2010/2017 x=2/9 {
    count if firstyear==2009 & lastyear==`y' & count==`x'
    }
    Ofcourse, I know that syntax is not valid, however you can tell what I'm trying to do, since the range (number of jumps) is the same for both y and x, then there should be some way of doing this. Please let me know. My goal is to be able to use both y and x macros simultaneously.

    Thanks,
    Jad



  • #2
    I can't tell easily what you want to do, as your attempted syntax is consistent with wanting parallel loops and also with wanting nested loops. If I had to guess I would guess parallel, but the question is still ambiguous.

    Those could be

    Code:
     * parallel  
    forvalues x=2/9 {
          count if firstyear==2009 & lastyear==`x' + 2008 & count==`x'
    }  
    
    * nested  
    forvalues y=2010/2017      
          forvalues x=2/9 {        
                count if firstyear==2009 & lastyear==`y' & count==`x'    
          }
    }
    However, I don't see why you are looping here at all. The results of those could be either 8 scalars or 64 scalars, depending on which you want. You should not want to trawl through output from several commands. when you can get results with one command. If you want to see the results, use tabulate. If you want a new variable, use egen.

    Code:
    tab lastyear count if firstyear == 2009  
    
    egen count = total(firstyear == 2009), by(count lastyear)
    are just some of the possibilities. Depending on what else is going on or wanted, you may need to add extra code, or to use something with similar flavour but different details.

    See https://journals.sagepub.com/doi/pdf...6867X211063415 for a tutorial review on parallel loops.
    Last edited by Nick Cox; 04 May 2024, 03:10.

    Comment


    • #3
      In #2 you need a new name for the new variable:


      Code:
      egen count2 =
      Or whatever. Sorry if anyone was misled by the code.

      Comment


      • #4
        Hello Nick,

        Yes, I wanted a parallel loop, the syntax you provided does the trick, I will also explore the other option as well. Thanks!

        Comment


        • #5
          The tabulation worked very nicely thanks!

          Comment

          Working...
          X