Statalist The Stata Listserver


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

Re: st: Question using macro in loop


From   Friedrich Huebler <[email protected]>
To   [email protected]
Subject   Re: st: Question using macro in loop
Date   Thu, 5 Apr 2007 20:51:18 -0700 (PDT)

Tak Wai,

The loop below copies all non-missing observations from variables v1
to v10 to variables w1 to w10. The macro s counts the number of
non-missing observations in variables v1 to v10.

local s = 0
forvalues i = 1/10 {
  replace w`i' = v`i' if v`i'<.
  count if v`i'<.
  local s = `s' + r(N)
  di `s'
}

The statement "s=1" is not valid Stata, you probably mean "generate
s=1". The command "local s1=s" assigns the first observation in
variable s to the local s1. The command "replace s=s+1 if v`i'<."
adds 1 to all observations in variable s if the first observation in
variable v`i' is missing.

The command "replace w`s1'=v`i' if v`i'<." indicates that you may be
thinking in terms of a loop over observations, not variables. Such a
loop is neither efficient nor necessary but if you want it you need
different code from the one above.

Friedrich

--- Tak-wai Chau <[email protected]> wrote:
> Hi,
> 
> I would like to ask something about using macro in loops. I have
> tried to find it in the archive and FAQ for some time but I don't
> get it.
> 
> Sorry if I have overlooked some obvious things.
> 
> I would like to update certain variables according to the value
> taking by a particular variable, and this value differs by
> observations. Then what I should do?
> 
> For example, if I want to transfer value of non-missing variables
> from V1-V10 to W1-W10. But I don't want to variables carrying 
> missing value between. I use s to count the number of non-missing
> values I have covered at that point.
> 
> The following is what I think of but doesn't work.
> 
> s=1
> forvalues i=1/10 {
> 	local s1=s
> 	replace w`s1'=v`i' if v`i'<.
> 	replace s=s+1 if v`i'<.
> }
> 
> I know the problem is at the local statement.
> 
> What should I do?
> 
> Thank you very much!
> 
> Tak Wai Chau








 
____________________________________________________________________________________
Don't pick lemons.
See all the new 2007 cars at Yahoo! Autos.
http://autos.yahoo.com/new_cars.html 
*
*   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