0
votes

I want to generate a variable with lagged year depending on the year stored in the "$S_DATE" macro. I have stored the year in a macro named date:

. local date substr("$S_DATE",8,.)
. display `date'
  2015

And I want to generate the new variable with:

gen start_year =`date'- y_passed

where y_passed is a variable containing integers from 1 to 10.

However, I get:

. gen start_year = `date' - y_passed
type mismatch
r(109);

I know this happens because the macro stored is a string.

How can I change the value stored in local macro from string to numeric?

1

1 Answers

2
votes

If you add =, then Stata will evaluate the expression that defines local date:

clear
set more off

set obs 10
gen y_passed = _n

local date = substr("$S_DATE",8,.)
display `date'

gen start_year = `date' - y_passed

list

Otherwise, the local just holds a string, but not a number in a string type! See

. local date substr("$S_DATE",8,.)

. display `"`date'"'
substr("14 May 2015",8,.)

The confusion is because display will evaluate for you. In reality,

display `date'

expands to

display substr("14 May 2015",8,.)

and the latter results in

2015