I wrote a program a while back to put variables into a series of
macros based on the variable names. The macros have a prefix _ma_ and
rows are numbered with a _## suffix so that macros look like
_ma_varname_##. I offer the code below - the lines will probably
wrap, so be careful. If you wish to contact me offlist, I could
arrange to eMail this to you along with the help file. I really
should release this to SSC, I suppose it might be of use to someone
else. Obviously one would not want to use this on large datasets!
x--------------Begin code------------------x
*! version 1.0.0 2006.05.08
program define makemacro, rclass /* Makes consecutively numbered
macro variables from a data file values */
version 9.0
preserve // Preserve the data file if one is open
// This code takes a data file and turns it into a series of
consecutively numbered macros,
// one for each row, containing the values for each variable, enclosed
in quotes.
// The macros (ma_variable_name_1, ma_variable_name_2...ma_variable_name_n)
// can be addressed in a loop, using `"`ma_variable_name_`i''"' for
use in other commands
// The quiet option suppresses output of a summary statement.
syntax anything(name=procfile id="A data filename is") [, Quiet]
capture confirm file `procfile' // First try what was passed
if _rc!=0 {
local procfile `procfile'.dta // Add a .dta extension and try again
capture confirm file `procfile'
if _rc!=0 { // Still no luck, exit with an error message
di "{p}{err}syntax is {cmd:makemacro {it:datafilename[.dta]}} ///
and the datafile was not found...{p_end}"
exit 198
}
}
use `procfile'
macro drop _ma_* // Drop any previous arrays and counts
local ma_rows = _N
local ma_cols = `c(k)' // Number of variables in dataset
return local ma_rows = _N
return local ma_cols = `c(k)'
tempname temp
forvalues row = `ma_rows'(-1)1 { // Loop in reverse
foreach var of varlist * {
c_local ma_`var'_`row' `=`var'[`row']'
}
}
if "`quiet'" != "quiet" {
foreach var of varlist * {
local varnames = "`varnames' "+"ma_`var'_##"
}
di "Variables: `varnames'"
di _n in ye `ma_cols' in gr " macro arrays of length " in ye ///
`ma_rows' in gr " are stored as:" _n in ye "`varnames'"
}
restore
end
x--------------End code------------------x
I've been musing about adding a varlist option so that only selected
variables are placed in the macro array - tell me what you think.
David Elliott
*
* For searches and help try:
* http://www.stata.com/help.cgi?search
* http://www.stata.com/support/statalist/faq
* http://www.ats.ucla.edu/stat/stata/