Search code examples
stringforeachstata

"too few quotes" error message when trying to use foreach value as a string


I'm trying to append panel data for seven files using a foreach loop.

I know the code in Stata to append and understand the foreach command.

This is the code I have, which I assume is correct:

use "C:\Users\main\Documents\German patent applications 1996.dta"

foreach k in 1997 1998 1999 2000 2001 2002{
    append using "C:\Users\main\Documents\German patent applications "'k'".dta"  
}

It should append the data for all the seven files into one data set containing data for the years 1996-2002.

However, when I run this code i get the error message:

too few quotes r(132)

I'm clearly trying to use the k value as a string in the filename so it can be appended.

What am I doing wrong and how can I fix this?


Solution

  • Assuming the file name is of the form:

    German patent applications 1997.dta
    

    The following works for me:

    foreach k in 1997 1998 1999 2000 2001 2002{
        display "C:\Users\main\Documents\German patent applications `k'.dta"
    }
    
    C:\Users\main\Documents\German patent applications 1997.dta
    C:\Users\main\Documents\German patent applications 1998.dta
    C:\Users\main\Documents\German patent applications 1999.dta
    C:\Users\main\Documents\German patent applications 2000.dta
    C:\Users\main\Documents\German patent applications 2001.dta
    C:\Users\main\Documents\German patent applications 2002.dta