Stata The Stata listserver
[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

st: RE: looping through vectors


From   "Nick Cox" <[email protected]>
To   <[email protected]>
Subject   st: RE: looping through vectors
Date   Wed, 28 May 2003 10:56:23 +0100

Patrick Sturgis

> I have two vectors of variables, X and Z. I wish to copy 
> the values of each
> of the elements of Z to the corresponding (in terms of 
> variable order)
> element in X. Would the 'foreach' command be most suitable 
> for this purpose
> or would something simpler suffice? Thanks in advance,

I guess that a vector of variables Z is a set of variables. 

In the easiest case you have some simple naming like 
Z1 ... Z42. 

To copy that to X1 ... X42 you can go 

forval i = 1/42 { 
	gen Z`i' = X`i' 
} 

(for -gen- read -replace- if that is what you want).

For a messier case with irregular suffixes like 

Zbill, Zvince, Zalan, Zpat, Zbobby, Zchinh, Zken, etc. 

for which you want the corresponding 

Xbill, Xvince, Xalan, ... 

one way of doing it is 

foreach v of var Z* { 
	local new : subinstr local v "Z" "X" 
	gen `new' = `v' 
} 

See -whelp macro-. 

Sometimes with just a few suffixes it can be 
easiest just to go 

foreach s in bill vince alan { 
	gen X`s' = Z`s' 
} 


Nick 
[email protected] 
*
*   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