Announcement

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

  • saving two files using foreach

    Dear statalist,

    I tried to load two files, make some changes, and save them in one go. However I just could not get it right.
    Appreciated it in advance if anyone could point me the correct way.


    Code:
    global ylist "insurance mutual pension"
    
    foreach file of local "emerging" "advanced" {
        import delimited `file'.csv, varnames(1) case(upper) clear 
        encode COUNTRYNAME, gen(COUNTRY)
        drop COUNTRYNAME
        rename *, lower
        foreach var of global $ylist {
            rename `var' `var'_`file'
        }
        xtset country year
        save `file', replace
    }

  • #2
    foreach file of local "emerging" "advanced"
    is not valid Stata syntax. You must first create, and name, a local macro that contains "emerging" and "advanced" and then refer to that by its name in the -foreach- command. So:

    Code:
    local filenames emerging advanced
    foreach file of local filelist {
        import delimited `file'.csv, varnames(1) case(upper) clear
        encode COUNTRYNAME, gen(COUNTRY)
        drop COUNTRYNAME
        rename *, lower
        foreach var of global $ylist {
            rename `var' `var'_`file'
        }
        xtset country year
        save `file', replace
    }
    As an aside, the use of global macros (I'm referring to ylist) is an unsafe programming practice that should only be used when no suitable alternative is available. There is no reason why this same information cannot be stored as a local macro.

    Comment


    • #3
      Thank you Clyder, it works now. appreciated your suggestion on global/local macros too

      Comment


      • #4
        Clyde Schechter meant

        Code:
         local filelist emerging advanced
        
        foreach file of local filelist {
        while

        Code:
        foreach file in emerging advanced {
        should work too
        Last edited by Nick Cox; 08 Mar 2023, 19:52.

        Comment

        Working...
        X