Announcement

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

  • "already preserved" error when running preserve and restore in a loop

    Hello community.

    I am trying to run this loop with preserve and restore, however, when I run the code it says throws "already preserved" even when I am including the restore command at the end of the loop.

    Any idea of what is the problem?
    This is the code:

    foreach country_name in "Antigua and Barbuda" "Argentina" "Aruba" "Bahamas" "Barbados" "Belize" "Bermuda" "Bolivia" "Brazil" "British Virgin Islands" "Cayman Islands" "Chile" "Colombia" "Costa Rica" "Cuba" "Curacao" "Dominica" "Dominican Republic" "Ecuador" "El Salvador" "Equatorial Guinea" "Grenada" "Guatemala" "Guyana" "Haiti" "Honduras" "Mexico" "Nicaragua" "Panama" "Paraguay" "Peru" "St. Kitts and Nevis" "St. Lucia" "St. Martin (French part)" "St. Vincent and the Grenadines" "Trinidad and Tobago" "Uruguay" "Venezuela, RB" {
    preserve
    drop if Country!= "`country_name'"
    tsset year
    dfuller ln_CO2_emissions_kt, lags(0)
    dfuller ln_CO2_emissions_kt, lags(1)
    dfuller ln_CO2_emissions_kt, lags(2)
    dfuller ln_Energy_use_oil_kg_equ, lags(0)
    dfuller ln_Energy_use_oil_kg_equ, lags(1)
    dfuller ln_Energy_use_oil_kg_equ, lags(2)
    dfuller ln_GDP_constant2015_USD, lags(0)
    dfuller ln_GDP_constant2015_USD, lags(1)
    dfuller ln_GDP_constant2015_USD, lags(2)
    restore
    }

  • #2
    I don't immediately see what is going wrong. But you can use frames instead, which seems to work.

    Code:
    frames reset
    
    frame create data // store the whole data in frame data
    frame change data
    sysuse nlsw88
    
    levelsof industry
    local levs = r(levels)
    
    frame create playground // this frame we can change as we wish
    frame change playground
    
    foreach lev of local levs{
        frame copy data playground, replace // get the whole data again
        
        keep if industry == `lev' // select the subsample
        sum wage                  // do stuff to that subsample
    }
    ---------------------------------
    Maarten L. Buis
    University of Konstanz
    Department of history and sociology
    box 40
    78457 Konstanz
    Germany
    http://www.maartenbuis.nl
    ---------------------------------

    Comment


    • #3
      dfuller seems to work fine if you specify a single panel, so the file heaving seems unnecessary.

      In addition, see Method 1 in https://www.stata.com/support/faqs/d...-with-foreach/ for an easier way to loop over panels.

      Comment

      Working...
      X