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

st: re: averaging over a whole bunch of variables


From   Kit Baum <[email protected]>
To   [email protected]
Subject   st: re: averaging over a whole bunch of variables
Date   Tue, 12 Jul 2005 23:14:41 -0400

Then Kelly said

now suppose I had to do this operation in 100 different variabes (call them
var1-var100), how can i code a simple loot to do that?

i want to perform this within each variable: gen Var2=(Var1+Var1[_n-1])/2
if mod(_n,2)==0

(even _n calculations are fine...)

Thanks!


Generalization of the last solution. Hardly likely to be the most elegant way to skin this particular feline, but---

clear
set obs 100
forv i=1/100 {
g var`i' = _n+`i'-1
}

// define the avg function and save as .mo (compiled object)

mata:
void avg(string vname)
{
vnew = vname + "A"
v1=st_data(.,vname,0)
v3 = colshape(v1',2) * J(2,1,0.5)
res=st_addvar("float",vnew)
st_store((1,rows(v3)),res,v3)
}
mata mosave avg(), replace
end

// now apply the avg function to each of the 100 variables; name the averaged version of each with
// suffix A

forv i=1/100 {
mata avg("var`i'")
}



Kit Baum, Boston College Economics
http://ideas.repec.org/e/pba1.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