-1

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)
Cenk
  • 325
  • 4
  • 16

1 Answers1

2

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
  • 1
    ??? the new variable is just the old variable + 1955. `generate year = Year + 1955`. !!! – Nick Cox Aug 09 '18 at 16:21
  • 1
    Sure, but it's a disservice not to point out an easier solution --- as happened to me in reverse only a few hours ago on Statalist. – Nick Cox Aug 09 '18 at 16:22