0

I have a list of files with similar names, for example:

  • 2002_file
  • 2003_file
  • 2004_file

I am going to run a simple script:

foreach year in 2002 2003 2004 2005 2006 2007 2008 2009 2011 2012 2013 2014 2015 {  
use "$input\`year'_file.dta ", clear
keep v1 v2 v3
tab v1, gen (v1_dummy)
gen year = 'x'
save "$output\`year'_newfile.dta ", replace
}

However, I would like for one of the files to be created the respective year variable.

How can I add a variable year = 'year' ?

j_3265
  • 207
  • 3
  • 12

1 Answers1

2

You do not define the local macro x anywhere.

The following should work:

foreach year in 2002 2003 2004 2005 2006 2007 2008 2009 2011 2012 2013 2014 2015 {
    use "$input\`year'_file.dta ", clear
    keep v1 v2 v3
    tab v1, gen (v1_dummy)
    gen year = `year'
    save "$output\`year'_newfile.dta ", replace
}

For a specific year only:

foreach year in 2002 2003 2004 2005 2006 2007 2008 2009 2011 2012 2013 2014 2015 {
    use "$input\`year'_file.dta ", clear
    keep v1 v2 v3
    tab v1, gen (v1_dummy)
    if `year' == 2005 gen year = `year'
    save "$output\`year'_newfile.dta ", replace
}
  • You're right, I corrected the question! Every case makes no difference, this mistake I made now writing the question and adapting the example. – j_3265 Jun 25 '18 at 21:58
  • 1
    @JoyceMaia Do you want the variable to be added in the new file for a specific year only? –  Jun 25 '18 at 23:25
  • I need to make this part of the filename that matches the year a variable (gen year = `x '), but I do not know how. – j_3265 Jun 26 '18 at 01:44
  • The error was the lack of quotes "` x '" or "` year'". – j_3265 Jun 26 '18 at 02:19
  • 1
    @JoyceMaia You do not need quotes. If you use quotes you will create a string `year` variable instead of a numeric one. –  Jun 26 '18 at 11:39
  • If I do not put it as a string, for some reason an error occurs when saving the new file names. Saves as `x' instead of years. – j_3265 Jun 29 '18 at 00:54
  • @JoyceMaia Sorry but i cannot reproduce your problem. The altered code snipped that i provided above works as expected on my computer. –  Jun 29 '18 at 09:42