Sequentially name variables

Sometimes we need to apply foreach loop or other loops to variables. In that case we need to assign names to variable sequentially, for example if we have stock returns where the data is in wide format and each stock appears as variable name. In that case the individual identity of the stocks is not important as they are lumped into portfolios. To give all the stocks sequential names, we can use the following loop:

loc A "1"

foreach v of varlist _all {

    ren `v' VAR` = `A' + 1'

    loc l = `A' + 1


If you need your variables to be ordered sequentially, you can use:

order *, sequential