Announcement

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

  • Looping through filenames

    Hello all,

    I have filenames 1992Germany 1996Germany 1992Korea 1996Korea (I have years 1992, 1996,1997,2001,2002,2006 and about 9 countries)

    I wanted to loop through these different files and was struggling how to do it. Also for each file, I will be creating a new variable. For instance for 1992Germany, I will create a variable TradeGermany1992; for 1996Germany , I will create TradeGermany1992 and so on.

    I tried:
    local year 1992 1996 1997 2001 2002 2006
    local country Germany Korea

    foreach y local year{
    for each c local country{
    use `year'`country'.dta
    gen trade`country'`i'=trade*value
    save new`year'`country'.dta,replace
    }

    }

    But it doesn't run. Can you please give me ideas and how to loop those files. Thanks in advance.

  • #2
    maybe try something like the following assuming they are in one folder:

    cd <target directory>
    local files : dir . files "*.<type of file>"

    foreach f of local files {

    Comment


    • #3
      and for your variable you can use something like:

      g newvar="Trade`f'"


      Comment


      • #4
        Try:
        Code:
        local year 1992 1996 1997 2001 2002 2006
        local country Germany Korea
        
        foreach y of local year{
            foreach c of local country{
                use `y'`c'.dta, clear
                gen trade`c'`y'=trade*value
                save new`y'`c'.dta,replace
            }
        
        }
        The word "of" in the -foreach..of local..- syntax is not optional.
        Inside a loop, the current value of the loop parameter is given by the local macro that appears immediately after the word -foreach-, and it is to that which you must refer inside the loop. The macros year and country always contain the full list of countries and years, not the current values of country and year, so referring to them inside the loop is appropriate only if you need to use the entire list(s) for some purpose.

        Comment


        • #5
          Hey Clyde,

          That does work. Thank you for explaining what I did wrong there. I really appreciate it.

          Comment


          • #6
            You're welcome. At this point, let me just mention that the norm in this community is to use our full real names (given and family names) as our username, in order to promote collegiality and professionalism. Unfortunately, you can't change it by editing your profile. But if you would please click on CONTACT US in the lower right corner of your screen, you can send a message to the forum administrator requesting that he change your user name.

            Comment

            Working...
            X