Announcement

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

  • Read a list of variables in a loop, while ignoring some variables that don't exist

    Hello,

    I'm trying to use a list of variables that have suffixes based on years, using a loop. However, some variables only exist in several years, say we have comp_expnd2017 in the file, but not comp_expnd2015 in the file. When I use the loop, how can I ignore variables that don't exist in the file, and continue reading variables that exist?

    I looked into capture confirm variable, but it seems that it only works to confirm whether a variable exists in a varlist, not in a data file that isn't fully read into Stata memory. Thank you.

    Code:
    * Doing analysis based on years
    forvalues Y = 1999(2)2017 {
    
    * read in variables needed
    #delimit ;
    use
    personid
    famid`Y'
    age_head`Y'
    income`Y'
    hsng_status`Y'
    if_mortgage`Y'
    housing_expnd`Y'
    childcare_expnd`Y'
    healthcare_expnd`Y'
    edu_expnd`Y'
    trans_expnd`Y'
    food_expnd`Y'
    entmt_expnd`Y'
    trips_expnd`Y'
    clothing_expnd`Y'
    comp_expnd`Y' // only exist for comp_expnd2017, but not comp_expnd2015 or any years before 2017
    using $madir/real_sav_master.dta, clear; // this master file contains all the variables
    #delimit cr
    
    * some other codes for analysis, omitted here
    }

  • #2
    Instead of adding the comp_expnd variable in the initial -use- command, add it as a merged variable afterwards:

    Code:
    cap merge 1:1 personid using yourfile.dta,keepusing(comp_expnd`Y');
    This will let you bring in all of the other variables while only bringing in comp_expnd when it exists.
    Last edited by Ali Atia; 17 Mar 2021, 07:15.

    Comment


    • #3
      Thank you so much Ali. It really helps

      Comment

      Working...
      X