Statalist The Stata Listserver

[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

Re: st: how to make a string matrix

From   "David Elliott" <>
Subject   Re: st: how to make a string matrix
Date   Tue, 15 May 2007 16:34:24 -0300

On 5/15/07, Kit Baum <> wrote:
sacrificial rutabaga
I checked, but according to Google, that is the only mention of
"sacrificial rutabaga" on the internet!

But back to the game at hand.

I had written a routine a while back that turns a dta file into a
macro array.  It illustrates how simply such an array can be

*! version 1.0.0  2006.05.08
program define makemacro, rclass /* Makes consecutively numbered
                                   macro variables from data file values */
version 9.0
preserve        // Preserve the data file that 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

foreach var of varlist * {
   local varnames = "`varnames' "+"ma_`var'_##"
   di "Variables: `varnames'"
forvalues row = `ma_rows'(-1)1 {    // Loop in reverse
   foreach var of varlist * {
       c_local ma_`var'_`row' `=`var'[`row']'

if "`quiet'" != "quiet" {
   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'"

//Note: the mailer will probably wrap the comments

If the datafile has variables: group measure ifin, the resulting
macros would be in locals: `ma_group_`row'', `ma_measure_`row'' &

I use the routine to input a command file that allows me to loop

forvalues row=1/`ma_rows' {
   dosomething `ma_measure_`row'' if group=='"`ma_group_`row''"' &

For convenience I used the original variable names for part of the
macronames.  However, one could index things just as easily with

*   For searches and help try:

© Copyright 1996–2015 StataCorp LP   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index