Jump to content
Urch Forums

Stata. Repeated collapse


dcurious

Recommended Posts

I want to collapse (mean) "15 variables", by (household) + casewise

This is because different households have missings in different variables.

The problem is if I collapse them all at the same time, I will be deleting missing observations and not missing observations.

 

I am thinking on,

for each x-var in "15 variables", collapse x and save. Then append all the files.

 

It sounds easy, but How can I program it?

how can I make a repeated collapse and save for each variable?

any suggestion?

Link to comment
Share on other sites

If I understand correctly...

 

foreach var of varlist var1-var15 {

egen mean`var'=mean(`var'), by(household)

}

keep household mean*

duplicates drop

 

I think the above works, but you can also do it using a method similar to what you've outlined (collapsing on one, saving, reopening the original, collapsing..., then merging all 15 together at the end). It might look something like:

 

local i=1

tempfile temp

save `temp'

foreach var of varlist var1-var15 {

use `temp', clear

drop if `var'==.

collapse (mean)`var', by(household)

sort household

tempfile `i'

save ``i''

local i=`i'+1

}

 

use `1', clear

local i=2

while `i'

sort household

merge household using ``i'', unique

drop _merge

local i=`i'+1

}

Edited by Liwanyo
typos
Link to comment
Share on other sites

  • 3 years later...

I am working on panel data. I have to create the Rolling SD of Y variable.

 

Which I am able to create with the help of the “ssc install mvsumm”

 

The command for creating the 3 year moving SD is

 

mvsumm y, stat(mean) win(3) gen(`var'3avg) end

 

Here I am facing a number of issue/problems

 

As I have to do 3 year moving SD for number of variables.

 

So I am trying to use foreach command

 

This is the commands in do file

 

webuse grunfeld,clear

xtset company year

*** Code for calculating 3 Year moving SD**

global storelist ""

foreach var in y x {

global storelist = "${storelist} `var'"

mvsumm `var', stat(sd) win(3) gen(`var'3sd) end

collapse `var' , by(company)

 

}

 

Getting the following error message.

 

“variable x not found”

 

1) How I can over come this.

 

 

Link of the data file is

https://www.dropbox.com/s/29a31q104iw6an4/panel.xlsx

 

Regards

 

Sadia Khalid

Link to comment
Share on other sites

Guest
This topic is now closed to further replies.
×
×
  • Create New...