Search code examples
loopsstatastata-macros

Loop for recoding years


I would like to recode my variable named as Year using a for a loop and create a new variable named as year in Stata.

What I am looking for should shorten below-mentioned code:

recode Year (5 = 1960) (6 = 1961)(7 = 1962)(8 = 1963)(9 = 1964) (10 = 1965) ///
(11 = 1966) (12 = 1967) (13 = 1968) (14 = 1969) (15 = 1970) (16 = 1971) ///
(17 = 1972) (18 = 1973) (19 = 1974) (20 = 1975) (21 = 1976) (22 = 1977) ///
, gen(year)

Solution

  • The for loop will not shorten your code and there is no other way of writing this more succinctly.

    Nevertheless, the following works for me:

    local counter1 = 4
    local counter2 = 59
    
    forvalues i = 1 / 18 {
        local counter1 = `counter1' + 1
        local counter2 = `counter2' + 1
        local foo `foo' (`counter1' = 19`counter2')
    }
    
    recode Year `foo', generate(year)
    

    EDIT:

    As @NickCox points out (and i agree) instead of a loop you could do the following:

    generate year = Year + 1955