Announcement

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

  • Creating a loop over both letters and numbers

    Hi! I need to edit a number of files and am looking to create a loop to do so. There are two changes I need to do to each dataset:

    1. Remove variable prefix: each dataset has a letter prefix for all variables. The first dataset (w1_indresp.dta) has a, the second dataset (w2_indresp.dta) has b and so on...
    2. Generate a year variable: each dataset needs a year variable. The first dataset (w1_indresp.dta) needs year 1991, the second dataset (w2_indresp.dta) needs 1992and so on...

    The code below is the "non-loop" version for the first two datasets.

    use "/w1_indresp.dta"
    renpfix a
    gen year = 1991
    duplicates report pid
    save "w1_indresp_edit.dta", replace


    use "w2_indresp.dta"
    renpfix b
    gen year = 1992
    duplicates report pid
    save "w2_indresp_edit.dta", replace

    How can I create a loop that runs over both letters and numbers? I appreciate any help :-)

  • #2
    Consider the following:

    Code:
    di "`c(alpha)'"
    di word("`c(alpha)'", 3)
    Res.:

    Code:
    . di "`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
    
    . di word("`c(alpha)'", 3)
    c
    Therefore, you can refer to the number directly and use the -word()- function to refer to the corresponding letter in the alphabet.

    Comment


    • #3
      In similar spirit to Andrew Musau this code is good for a ... z and years 1991 to 2016 and will need modification otherwise:


      Code:
      tokenize `c(alpha)'
      
      forval j = 1/26 {  
      
      use "/w`j'_indresp.dta"
      renpfix ``j''
      gen year = 1990 + `j'
      duplicates report pid
      save "w`j'_indresp_edit.dta", replace
      
      }

      Comment

      Working...
      X