Announcement

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

  • Indexing within loop

    Dears Statalisters,
    I am facing a problem with a loop.

    I want to create a variable over three decades in a loop, that must be indexed.
    Basically, var8 must be associated with 1990, var9 with 2000 and var10 with 2010.

    .
    How can I do that?

    This is my previous code:


    Code:
    clear all
        
    foreach y of numlist 1990 2000 2010{
        forvalues i=8/10{
        use data.dta, clear
        
        keep if year==`y'
        gen county_`y' = statefip*10000+countyicp
        
        
    
    fcollapse (sum) a`y' b`y' c`y' d`y', by(f_`y' year county_`y') 
    
    gen var_`i' = f``y'*c`y'
    
    save data`y', replace
    
    }    
    }

    The code is wrong because after having generate var_8 for 1990 and saved the file, it starts again the loop and calculate var_9 for the same year and ovewwrite the old file.









  • #2
    What you need is a loop in parallel, not a nested loop. See https://journals.sagepub.com/doi/pdf...6867X211063415 for a detailed tutorial review.

    Here is one way to do it. I've corrected an incidental typo. I take as granted that you need three different datasets.

    fcollapse is from somewhere you should explain (FAQ Advice #12). Naturally I can't test this.

    Code:
    clear all
        
    local years 1990 2000 2010 
    
    forvalues i=8/10 {
        use data.dta, clear
        gettoken y years : years 
        keep if year==`y'
        gen county_`y' = statefip*10000+countyicp
        fcollapse (sum) a`y' b`y' c`y' d`y', by(f_`y' year county_`y') 
        gen var_`i' = f_`y'*c`y'
        save data`y', replace
    }

    Comment


    • #3
      Dear Nick,
      the code worked perfectly. Thank you.
      Thank you also for the reference on the tutorial review.

      I used fcollapse, discovered in this forum, to generate new dataset from a large dataset.

      I need indeed three different datasets to append later on in a new "county consistent" dataset.
      Thank you again.

      Comment

      Working...
      X