Bénédicte
Bénédicte

Reputation: 11

while loops in Stata

I am trying to create some loop to avoid having too many line code. Here is my current code. There are many redundancy, any way I can write it with a single loop? Many thanks!

replace WTP_ph = +87.5 if WTP_ph == -76
replace WTP_ph = +62.5 if WTP_ph == -50
replace WTP_ph = +37.5 if WTP_ph == -25
replace WTP_ph = +12.5 if WTP_ph == 0
replace WTP_ph = -12.5 if WTP_ph ==  +25
replace WTP_ph = -37.5 if WTP_ph ==  +50
replace WTP_ph = -62.5 if WTP_ph ==  +75
replace WTP_ph = -87.5 if WTP_ph ==  +76

replace WTP_pe = +87.5 if WTP_pe == -76
replace WTP_pe = +62.5 if WTP_pe == -50
replace WTP_pe = +37.5 if WTP_pe == -25
replace WTP_pe = +12.5 if WTP_pe == 0
replace WTP_pe = -12.5 if WTP_pe ==  +25
replace WTP_pe = -37.5 if WTP_pe ==  +50
replace WTP_pe = -62.5 if WTP_pe ==  +75
replace WTP_pe = -87.5 if WTP_pe ==  +76

replace WTP_pa = +87.5 if WTP_pa == -76
replace WTP_pa = +62.5 if WTP_pa == -50
replace WTP_pa = +37.5 if WTP_pa == -25
replace WTP_pa = +12.5 if WTP_pa == 0
replace WTP_pa = -12.5 if WTP_pa ==  +25
replace WTP_pa = -37.5 if WTP_pa ==  +50
replace WTP_pa = -62.5 if WTP_pa ==  +75
replace WTP_pa = -87.5 if WTP_pa ==  +76



Upvotes: 0

Views: 178

Answers (1)

Nick Cox
Nick Cox

Reputation: 37183

This is a start

foreach v in WTP_ph WTP_pe WTP_pa { 
    replace `v' = 87.5 if `v' == -76
    replace `v' = 62.5 if `v' == -50
    replace `v' = 37.5 if `v' == -25
    replace `v' = 12.5 if `v' == 0  
    replace `v' = -12.5 if `v' ==  25
    replace `v' = -37.5 if `v' ==  50
    replace `v' = -62.5 if `v' ==  75
    replace `v' = -87.5 if `v' ==  76
} 

Then we notice a pattern in the mapping, except that the outermost statements are different, so we could go

foreach v in WTP_ph WTP_pe WTP_pa { 
    replace `v' = 87.5 if `v' == -76
    replace `v' = 12.5 - `v' if inrange(`v', -50, 75)
    replace `v' = -87.5 if `v' == 76
} 

Upvotes: 1

Related Questions