Loop do-file with a few adjustments

#1
Hey guys.

So I've made a long do-file and I was wondering if there were a clever way to repeat parts of the do-file with a few changes? I'm doing a series of cross-national tests and I want to see what happens if I drop a single country and run all the tests again.

Basicly I want this


use file.dta

doing all sorts of recodes and preperations

LOOP HERE
[[[drop if country==18]]] <-- this is the part that I want the second loop in the do-file to include before

doing all sorts of regressions and tests

LOOP HERE

exit

Does it make any sense?
 
#2
Code:
 webuse grunfeld, clear

 levelsof company, local(com_level)
 
 foreach x of local com_level {
 
	mean invest if company != `x'
	
}

Hey guys.

So I've made a long do-file and I was wondering if there were a clever way to repeat parts of the do-file with a few changes? I'm doing a series of cross-national tests and I want to see what happens if I drop a single country and run all the tests again.

Basicly I want this


use file.dta

doing all sorts of recodes and preperations

LOOP HERE
[[[drop if country==18]]] <-- this is the part that I want the second loop in the do-file to include before

doing all sorts of regressions and tests

LOOP HERE

exit

Does it make any sense?
 
Last edited:
#3
Yeah, but it's a really long file and if I had to use the if-qualifier for each command it would still be double as long. I was hoping to do a magic command that allowed me to loop specific parts of the do-file just as it was and just add the "drop"-thing. If I understand you right, I would need to do something like this

reg var1 var2
reg var1 var2 if var1 !='x'

It's still two lines.... perhaps I'm just not getting it.
 
#4
The -preserve- -restore- version is (edited according to the suggestion of Dason)

Code:
webuse grunfeld, clear

levelsof company, local(com_level)

foreach x of local com_level {

preserve

drop if company == `x'

mean invest 

restore
}
You may also see whether it is necessary to wrap your commands as a program (see -help program-)

Yeah, but it's a really long file and if I had to use the if-qualifier for each command it would still be double as long. I was hoping to do a magic command that allowed me to loop specific parts of the do-file just as it was and just add the "drop"-thing. If I understand you right, I would need to do something like this

reg var1 var2
reg var1 var2 if var1 !='x'

It's still two lines.... perhaps I'm just not getting it.
 
Last edited:

Dason

Ambassador to the humans
#5
Just a FYI... If you want to post code it's best to wrap it in code tags

[noparse]
Code:
a <- 2
[/noparse]

Becomes

Code:
a <- 2
Which looks better, easily conveys where the code starts and stops, and best of all it preserves indentation. Please use those tags from now on. Thanks!