Search code examples
loopsstatacapturestata-macros

Keep a list of variables when some variables don't exist


For several countries, I have one dataset and I want to keep a list of variables (specified in a global vlist) for each of them. Some variables do not exist in some countries.

I want Stata to ignore the non-existence of these variables and execute the keep command for the rest of the variables. However, the problem is the additional for loop on the country-level, that I'm struggling to incorporate.

This question is similar to the one asked in these threads:

Ultimately, I want to end up with a dataset for each country that has only those variables specified in the vlist (minus the ones from the vlist that do not exist).

Here's the code, which is mostly taken from the thread above:

clear all
set obs 5

local vlist v0 v1 v2 v3 v4 v5

foreach v of local vlist { 
    generate `v' = runiform()
}

save country1.DTA, replace
save country2.DTA, replace
save country3.DTA, replace

global vlist_example v0 v1 v6          // v6 is not part of the dataset

foreach country in country1 country2 country3 {
   local keeplist = ""
      foreach i of global vlist_example {
          capture confirm variable `i'
              if !rc {
                  local "`keeplist' `i'"
          }
      }
keep `keeplist'     
save `country'beta2.DTA, replace 

}

However, this produces the following error:

rc not found
r(111);

I hope this sufficiently describes my problem, but please let me know if anything needs more explaining.


Solution

  • The main problem with your code is that you do not call each dataset to modify it accordingly.

    The following should give you what you want:

    clear all
    set obs 5
    
    local vlist v0 v1 v2 v3 v4 v5
    
    foreach v of local vlist { 
        generate `v' = runiform()
    }
    
    save country1, replace
    save country2, replace
    save country3, replace
    
    global vlist_example v0 v1 v6          // v6 is not part of the dataset
    
    foreach country in country1 country2 country3 {
        use `country'.dta, clear
        local keeplist ""
        foreach i of global vlist_example {
            capture confirm variable `i'
            if !_rc {
                local keeplist "`keeplist' `i'"
            }
        }
        keep `keeplist'     
        save `country'beta2, replace 
    }
    

    Note that after capture you need to type !_rc and not !rc.