Announcement

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

  • loop to append multiple files and add new variable

    Hi there,

    I have a number of files named filename1990.dta, filename1991.dta etc until 2018. I would like to write a loop doing two things:

    1) append the files, and
    2) create a variable 'year' corresponding to the file name (2004, 2005, 2006) to show me which year the data came from.

    thanks in advance for your help!

    Liza

  • #2
    Code:
    forval i= 1990/2018{
       use filename`i'.dta, clear
       gen year=`i'
       save filename`i'.dta, replace
    }
    use filename1990.dta, clear
    forval i=1991/2018{
       append using filename`i'.dta
    }
    save all.dta
    It may be possible to do all in one loop:

    Code:
    use filename1990.dta, clear
    gen year=1990
    forval i=1991/2018{
       append using filename`i'.dta
       replace year= `i' if missing(year)
    }
    save all.dta
    Last edited by Andrew Musau; 24 Apr 2020, 06:24.

    Comment


    • #3
      Brilliant, thanks

      Comment

      Working...
      X