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 was not able to recreate your error. It is likely that outside the loop there is another preserve currently active. Try check the codes and/or restart the Stata session to see if the problem persists.

    Unrelated, your code can be simplified to omit the need to type out all the countries:

    Code:
    levelsof Country, local(c_list)
    
    foreach country_name in `clist' {
    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
    }
    Last edited by Ken Chui; 16 May 2023, 15:31.

    Comment

    Working...
    X