Announcement

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

  • Stata for loop error

    Hi,

    I am trying to run the below loop in stata. But i get an error.

    Can someone help me. I am a beginner in using Stata.

    The variables fyear, B031, B031_av are already defined and available in the dateset.


    forvalues fyear = 2005 / 2022 {
    2. local count=0
    3. foreach l of local levels {
    4.
    . count=count+1
    5.
    . local B031_sum=sum(B031) if loc == 'l'
    6. B031_av = B031_sum/count
    7. }
    8.
    . }
    =exp not allowed

    Many thanks in advance.

  • #2
    Perhaps you intended B031_av = B031_sum/count to be replace B031_av = B031_sum/count?
    --
    Bruce Weaver
    Email: [email protected]
    Version: Stata/MP 18.5 (Windows)

    Comment


    • #3
      No that didnt help. Still have the error.

      Comment


      • #4
        -count = count + 1- is not legal Stata syntax. To increment the value of the local macro count you would write
        Code:
        local count = count + 1
        
        // OR
        
        local ++count
        On top of that, you are referencing another local macro, levels, which you have not defined.

        Code:
        local B031_sum=sum(B031) if loc == 'l'
        has three problems. First it isn't clear what loc is: it isn't defined anywhere in the code. But in any case, you can't have an -if- clause in a local macro declaration. -if- clauses restrict the set of observations which the command applies to. But defining a local doesn't apply to any observations in the data set.

        I'm also guessing that local B031_sum = sum(B031) doesn't do what you think it does. Because defining local macros is not an operation carried out on the data set, mentioning a variable by name is interpreted to refer just to the value of the first observation of that variable. So local B031_sum will be set to the value of the B031 in the first observation. As it isn't obvious to me what you actually want local B031_sum to be, I can't offer you alternate code.

        Finally there is the error in -B031_av = B031_sum/count- which was already pointed out in #2.

        Comment


        • #5

          @Clyde Schecher makes several good points as usual. BTW, he meant

          Code:
           local count = `count' + 1
          not
          Code:
          local count = count + 1 
          Last edited by Nick Cox; 27 Dec 2022, 05:00.

          Comment

          Working...
          X