Statalist The Stata Listserver


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

Re: st: Adding variables with common prefix


From   "R.E. De Hoyos" <[email protected]>
To   <[email protected]>
Subject   Re: st: Adding variables with common prefix
Date   Tue, 30 May 2006 14:10:38 +0100

Thanks for your advice Nick, I changed the code to use a scalar within the loop.

Rafa

----- Original Message ----- From: "Nick Cox" <[email protected]>
To: <[email protected]>
Sent: Tuesday, May 30, 2006 1:50 PM
Subject: RE: st: Adding variables with common prefix



A detail worth emphasising is that the original
code used a scalar only at the very last step.
This cannot of course reclaim any precision lost
by using locals previously. Often this won't
matter in practice, but not always.

Nick
[email protected]

n j cox

Look again at the help for -foreach-.

foreach v of var var* {

That is, you must specify that var* is a varlist.

I would also use a scalar here.

scalar mysum = 0
foreach v of var var* {
scalar mysum = mysum + `v'[1]
}
R.E. De Hoyos

I have a large list of variables with a common prefix, say
-var- (var1,
var2, var3...). I want to generate a scalar with the sum of these
variable's first observation. I tried the following loop, but
for some
reason that I can't see it is not working, it returns an
invalid syntax
error message:

local sum = 0
foreach v of var* {
local sum = `sum' + `v'[1]
}
scalar answer = `sum'

What is wrong with this code? Is there an alternative way of
adding up
variables with a common prefix?
*
*   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/

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