Announcement

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

  • Evaluate whether variable values are in the set of values in local

    Dear All,

    I have a set of different data and I can either go through it all or through specific years. The former is especially useful in debugging. Thus I want to pass a local with the relevant years at the beginning and reduce the set to those codes below.

    Here a toy example of the process:
    local relevant_years "1987 1996"

    clear all
    set obs 12
    gen id = _n
    gen year = 1985 + id

    list

    +-----------+
    | id year |
    |-----------|
    1. | 1 1986 |
    2. | 2 1987 |
    3. | 3 1988 |
    4. | 4 1989 |
    5. | 5 1990 |
    |-----------|
    6. | 6 1991 |
    7. | 7 1992 |
    8. | 8 1993 |
    9. | 9 1994 |
    10.| 10 1995 |
    |-----------|
    11.| 11 1996 |
    12.| 12 1997 |
    +-----------+


    local num_relevant_years : word count `relevant_years'

    if `num_relevant_years' > 0 {

    forvalues y = 1/`num_relevant_years' {

    local relevant_year : word `y' of `relevant_years'
    gen check_`y' = (year == `relevant_year')

    }

    egen check = rowtotal(check_*)
    keep if check > 0
    drop check check_*

    }

    list

    +-----------+
    | id year |
    |-----------|
    1. | 2 1987 |
    2. | 11 1996 |
    +-----------+
    As you can see, the code does what I want, but I find it rather clunky so I was wondering if there is a more elegant way to solve this, to check in one go whether the value in each row in the set of values in the local.

    Any help is greatly appreciated.
    Last edited by Mario GronertA; 09 Jun 2022, 13:23.

  • #2
    Code:
    local relevant_years 1987 1992 1996
    
    local relevant_years: list clean relevant_years
    local relevant_years: subinstr local relevant_years " " ", ", all
    display `"`relevant_years'"'
    
    keep if inlist(year, `relevant_years')
    This will work provided you specify no more than 249 distinct relevant years in your local macro.

    Comment


    • #3
      Code:
      local relevant_years 1987 1992 1996 
      
      gen tokeep = 0 
      
      foreach y of local relevant_years { 
            replace tokeep = 1 if year == `y' 
      } 
      
      keep tokeep

      Comment


      • #4
        Nick Cox has,, I believe a typo - the word "if" should appear in his last line between keep and tokeep (his code will retain only the variable tokeep)

        Comment


        • #5
          Rich Goldstein is utterly correct. Thanks and sorry.

          Comment


          • #6
            Clyde Schechter Nick Cox , thank you for your help.

            And thanks Rich Goldstein for proof reading!

            Much appreciated!

            Comment

            Working...
            X