# Loops and Preserve

#### minnari

##### New Member
I have this piece of code:

Code:
gen graph =.
preserve
forvalues v = 10(1)12 {
replace graph = v'
drop if  salesv' == 0 | salesv' ==. | salesv' < 0
gen prodv' = salesv'/prof_v'
egen prodmeanv'= mean(prodv')
gen yv' =  prodv'/prodmeanv'

gen percentilev' = 0
forvalues i = 10(10)90 {
egen pi'v' = pctile(salesv'), p(i')
gen absolute_i'v' = abs(salesv'-pi'v')
sort absolute_i'v'
gen min_i'v' = absolute_i'v'
replace percentilev' = i' if absolute_i'v' == min_i'v'
}
keep if percentilev' != 0

gen Yv' = .
gen idv' = _n
foreach i in varlist idv' {
replace Yv' = (yv'[i]+yv'[i+1])/2 if percentilev'[i] == percentilev'[i+1]
replace Yv'= yv' if percentilev'[i] != percentilev'[i+1]
}

duplicates drop percentilev', force

if graph == 12 {
twoway scatter Y12 percentile12, title("2012")

}
if graph == 11 {
twoway scatter Y11  percentile11, title("2011")

}
if graph == 10 {
twoway scatter Y10  percentile10, title(" 2010")
restore
}
after successfully running from 10 to 11, it stops and says "i" ambiguous abbreviation. Could someone please help explain and help me fix the problem?
I want to run the graphs for successive years. Every time I find the percentiles, it destroys the dataset so I want to restore it to the way it was before and run the loop to find the percentiles again.
P.S: Pay no attention to the code finding percentiles. I just want to know why the code is not working to the 12th year. Thanks!!