Looping across observations
People who stress that you very seldom have to do this in Stata are right. That's why I always forget how it's done. So here, for my reference and yours:
Today I looked at a table in .rtf format. It had test scores for a bunch of students in Poli Sci at the University of Cluj, in Romania. The table is simple: two columns, with the students' full names on the first and their respective test score on the second.
I tried to copy and paste this table straight into the Stata data editor and surprise: I got a single column, with twice the number of original rows and alternating names and scores. The odd-numbered rows had names, the even-numbered ones had scores. Evidently the RTF column delimiter looks like an end-of-line character to both Stata and Notepad++.
So here was my chance to loop across observations in order to turn this table back into the two-column format. The code is below:
set more off
count
local obs=r(N)/2
di `obs'
capture drop var2
gen var2=""
forvalues i=1/`obs' {
local there=`i'*2
local here=`there'-1
replace var2=var1[`there'] in `here'
}
drop if var2==""
destring var2, replace
There's not much to it. Looping across observations is intuitively simple, but it's awfully inefficient. Do it if you must with small data sets, but consider alternatives, which are plentiful, if you are dealing with thousands of observations.