non-numeric_argument
non-numeric_argument

Reputation: 658

How to get the original value labels from a tempvar in a Stata program?

I have a program which does some calculation and saves some result matrices. I would like to use a sub-program which gets passed on some arguments from the main programm to name the columns and rows of the result matrices. In the best case, the value labels of the original variable in my dataset should be used for the row names of the matrices. However, I cannot figure out how to get the value labels from the original variable when I am passing on the variable. In the main program, I use syntax varname, rowvar(varname). Here is an example code:

*** Sub-program name matrix rows and cols ***
program namemat
version 6.0
args rowvar

tempname rowlab tmp_min tmp_max tmp_rowlab

mat def exmat = J(13,3,0)
qui sum `rowvar'
local tmp_min = r(min)
local tmp_max = r(max)
foreach i of numlist `tmp_min' / `tmp_max' {
    local tmp_rowlab:  label (`rowvar') `i'
    local rowlab = `"`rowlab'"' + `""`tmp_rowlab'" "'
}
matrix colnames exmat = "col 1" "col 2" "col 3"
matrix rownames exmat = `rowlab'

mat list exmat
end


*** Use subprogram ***
sysuse nlsw88, clear
namemat occupation

How can I get the original value labels from the 13 occupations as rownames? In the next coding step, I would save value labels which are too long in an additional scalar which I would then store along with the matrices as rclass results.

Upvotes: 0

Views: 372

Answers (1)

Nick Cox
Nick Cox

Reputation: 37208

This works for me:

*** Sub-program name matrix rows and cols ***
program namemat
version 6.0
args rowvar 
mat def exmat = J(13,3,0)
sum `rowvar', meanonly 

forval i = `r(min)'/`r(max)' {
    local rowlab  `"`rowlab' "`: label (`rowvar') `i''" "' 
}
matrix colnames exmat = "col 1" "col 2" "col 3"
matrix rownames exmat = `rowlab'

mat list exmat
end


*** Use subprogram ***
sysuse nlsw88, clear
namemat occupation

EDIT: Your problem is using tempname rowlab which means that the local macro rowlab starts out in life as a temporary name like __000000 Moral: don't use tempname when you're defining a local macro.

Upvotes: 1

Related Questions