# Re:st: using matrix expression

 From n j cox To statalist@hsphsun2.harvard.edu Subject Re:st: using matrix expression Date Tue, 03 Oct 2006 09:05:30 +0100

Seyda G Wentworth wrote

---------------------------------------------------------------------
I have thousands of observations (individuals) and earnings data for each of them covering 53 years, in the form earnings1951, earnings1952,...,earnings2003.
I'd like to convert those nominal earnings to 2003 dollars.
I have a price index variable called cpi with 53 values * for each of the 53 years, where the first value is equal to cpi1951/cpi2003, the second is cpi1952/cpi2003 etc. The remaing values are missing (because I copied a column created in excel).
I'm trying to write a mini program that'll compute real earnings (in 2003 dollars) for all individuals the following way:

gen j=0
. program define real
1. local i=1951
2. while (`i'<=2003) {
3. replace j=`i'-1950
4. gen realearnings`i'=earnings`i'/cpi[`j',1]
5. local i=`i'+1
6. }
7. end

But the results I get are incorrect. To check why, I try:

gen realearnings1951=earnings1951/cpi[1,1]

and get an error message saying:

r(111);

What is the correct way of doing this computation?
-----------------------------------------------------

and Rodrigo Alfaro replied

---------------------------------
You refer cpi[] as a matrix but you told us it is a variable.
try something like

forvalues i=1951/2003 {
local k=`i'-1950
local factor = cpi in `k'
gen realearnings`i'=earnings`i'/`factor'
}
---------------------------------

Proceeding on Rodrigo's assumption, namely that

-cpi- is a variable with non-missing values in 1/53 for years 1951/2003

then his code can be fixed and compressed to

forval i = 1951/2003 {
local k = `i' - 1950
gen realearnings`i' = earnings`i' / cpi[`k']
}

and even to

forval i = 1951/2003 {
gen realearnings`i' = earnings`i' / cpi[`=`i' - 50']
}

The bug here lurks in

local factor = cpi in `k'

which should be

local factor = cpi[`k']

All other changes are stylistic.

Nick
n.j.cox@durham.ac.uk

*
* For searches and help try:
* http://www.stata.com/support/faqs/res/findit.html
* http://www.stata.com/support/statalist/faq
* http://www.ats.ucla.edu/stat/stata/