1

I have the following code:

hist house1 if house1 >0 & house1 <200000, bin(25) fraction by(Year) 

graph export house1.png, replace

I would like to iterate it substituting house1 with car1 and bed1 without copy-pasting the code and substituting, or at least something like:

var = "house1"

hist var if house1 >0 & house1 <200000, bin(25) fraction by(Year) 

graph export var.png, replace

So that I can change just the value assigned to var.

fedpug
  • 15
  • 3
  • 1
    Welcome to Stack Overflow. Please read the [Stata tag wiki](https://stackoverflow.com/tags/stata/info) for advice on how to ask Stata-related questions on here. –  Jul 18 '19 at 17:25
  • 1
    We can't tell how literally to take your example, but you're implying that the same limits apply to quite different variables. @PearlySpencer is taking your example directly without trying to guess what you really want, which is more than reasonable. – Nick Cox Jul 18 '19 at 17:29

1 Answers1

2

A simple foreach loop will work:

foreach x in house1 car1 bed1 {
    display "hist `x' if `x' >0 & `x' <200000, bin(25) fraction by(Year)"
    display "graph export `x'.png, replace"
}

hist house1 if house1 >0 & house1 <200000, bin(25)fraction by(Year)
graph export house1.png, replace
hist car1 if car1 >0 & car1 <200000, bin(25)fraction by(Year)
graph export car1.png, replace
hist bed1 if bed1 >0 & bed1 <200000, bin(25)fraction by(Year)
graph export bed1.png, replace

Here x is a local macro that gets the values specified in foreach.

Note that the display command is used for illustration and is not necessary.