Announcement

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

  • IF EXISTS equivalent when keeping variables

    Hello,

    I have the following loop which reads in multiple files and saves them - I only want to keep certain variables in the files that are read in. All the files will have at least one of the variables listed in the "keep" clause of the code, most will have all three, but some only one, others will have two.

    Is there a way to rewrite the code to say, if one or more of the variables listed exist - then keep them? At the moment the code ends in error if one of the variables is not present


    foreach x of newlist DEM DEP MH AST COPD CVDPP CAN AF HYP CHD HF STIA RA BP SMOK DPE RTR CHY OSTIA {

    use "$path\QOF_`x'.dta", clear
    *
    keep GPCode Prevalence1920_* PCScore1920_* ExcptRate1920_*

    destring _all, ignore(":") replace
    save qof_`x'.dta, replace

    }

  • #2
    Daniel:
    what about the -no stop- option, -do- file entry, Stata .pdf manual?
    Kind regards,
    Carlo
    (Stata 18.0 SE)

    Comment


    • #3
      Instead of

      Code:
      keep GPCode Prevalence1920_* PCScore1920_* ExcptRate1920_*
      do something like this

      Code:
      local varlist 
      
      foreach v in GPCode Prevalence1920_* PCScore1920_* ExcptRate1920_* { 
      
          capture ds `v'  
          local varlist `varlist' `r(varlist)' 
      
      } 
      
      keep `varlist'

      Comment


      • #4
        When I need to do this I use the -isvar- package which can accept multiple variables as arguments and return those found in `r(varlist)'.

        Comment


        • #5
          . ssc desc isvar

          --------------------------------------------------------------------------------------------------------
          package isvar from http://fmwww.bc.edu/repec/bocode/i
          --------------------------------------------------------------------------------------------------------

          TITLE
          'ISVAR': module to filter names into variable names and others

          DESCRIPTION/AUTHOR(S)

          isvar takes a list of names that might name variables in your
          dataset and filters it into a list of those names that are
          indeed variable names and a list of the others.

          KW: variable names
          KW: data management

          Requires: Stata version 8.0

          Distribution-Date: 20050921

          Author: Nicholas J. Cox, Durham University
          Support: email [email protected]


          INSTALLATION FILES (type net install isvar)
          isvar.ado
          isvar.hlp
          --------------------------------------------------------------------------------------------------------
          (type ssc install isvar to install)

          Comment

          Working...
          X