Statalist The Stata Listserver


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

Re: st: Date: Sat, 31 Mar 2007 12:56:37 +0200


From   Phil Schumm <[email protected]>
To   [email protected]
Subject   Re: st: Date: Sat, 31 Mar 2007 12:56:37 +0200
Date   Sun, 1 Apr 2007 11:32:03 -0500

On Mar 31, 2007, at 5:57 AM, Maarten Buis wrote:
--- [email protected] wrote:
My problem is that I need to return some colvector matrices in stata as variables to be used later. I don't know how to do that:

for (i=1; i<=cols(Z1); i++) {
printf("i=%g\n",i)
Z1i = Z1[1...,i]
nomx = ("Z1i")
stata("cap drop Z1i")
// I tried "cap drop Z1`i'", not working
st_addvar("double",nomx)
st_store(.,nomx,Z1i)
}

My matrice Z1 has 3 columns. I want to create Z11 Z12 Z13 as new variables in my datasets. But in Stata I only get Z1i as a variable.
I am no mata expert, all I can tell you is what I found in the helpfiles:
I don't think it is necessary to loop here: -help mf_st_addvar- tells me you can create multiple variables in one go and -help mf_st_store- tells me you can store a matrix.

Maarten is of course correct here. For example, suppose your matrix Z1 is numeric and has the same number of rows as your dataset in memory, and that you have no variables named Z11,...,Z1n. In that case, all you need is the following:


newvars = st_addvar("float", "Z1":+strofreal((1..cols(Z1))))
st_store(.,newvars,Z1)


where you can replace the "float" in the call to -st_addvar()- with "double", if necessary. If you cannot depend on your dataset having the same number of observations as Z1 has rows, then you could use something like


if (st_nobs()<rows(Z1)) stata(sprintf("set obs %f",rows(Z1)))
newvars = st_addvar("float", "Z1":+strofreal((1..cols(Z1))))
st_store((1::rows(Z1)),newvars,Z1)


instead. Production code would, of course, need to handle the possibility that the vars Z1,...,Zn already exist, and, in fact, in many cases you would want to be using temporary variables instead.


-- Phil

*
* 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/




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