Announcement

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

  • Looping through two different sets of values

    I have data from several years. Each is stored in a file entitled "year 1" "year 2" .... "year 8". The variable names are the same each year, but in year 1 the variable names are prefixed a_, in year 2 b_, etc. I want to keep a subset of the variables each year, saving as new files while leaving the original files untouched. My code to do this is

    Code:
    use "filepath for data year 1"
    keep a_var1...a_var99
    save "filepath working data year 1"
    
    use "filepath for data year 2"
    keep b_var1...b_var99
    save "filepath working data year 2"
    
    ...
    
    use "filepath for data year 8"
    keep h_var1...h_var99
    save "filepath working data year 8"
    but I think it should be possible to create a loop rather than use repetitive code. My problem is I can't figure out how to loop over both 1-8 for the file names and a-h for the variable names, or how to restrict the combinations so that a is only called with 1, b with 2, etc. Can someone give me a pointer here?

    (I know I could just change the file names to be letters instead of numbers, but being able to combine two loops seems like a useful skill to have.)


  • #2
    Code:
    tokenize "`c(alpha)'" 
    
    forval y = 1/8 { 
    
        use "filepath for data year `y'"
        keep ``y''_var* 
        save "filepath working data year `y'"
    
    }
    You could

    Code:
    tokenize "a b c d e f g h"
    if you preferred. To see what c(alpha) contains,

    Code:
    . display "`c(alpha)'"
    a b c d e f g h i j k l m n o p q r s t u v w x y z
    
    . display c(alpha)
    a b c d e f g h i j k l m n o p q r s t u v w x y z

    Comment


    • #3
      That worked perfectly, thank you!

      Comment

      Working...
      X