I often use -levelsof- to loop through the levels of an unequally spaced variable. It is a fundamental loop that Nick Cox has described in various writings, e.g., Cox, N. J. 2002. Speaking Stata: How to face lists with fortitude. Stata Journal. 2: 202–222.
The problem with this type of loop is that with too many levels we hit into the Stata limits. An easy solution is to save the levels not in a local, but rather in a new variables.
Therefore I want to write a command that takes a variable ID, 1) preserves the current sort order of the data, and 2) creates a new variable LevelsOfID which contains the levels of ID in increasing order, with the first level in the first observation, the second level in the second observation and the last Nth level in the Nth observation.
About a week ago I wrote some double loop, from which I get headache now when I am reading it, and more importantly it fails in the following way. It calculates the levels, but I either mess up the original sort order, or I have the levels scattered all over the place. So my double loop violates either my 1) or my 2).
Today I had a second go from scratch, and I am still failing. Here is my new attempt:
Code:
program define levelstovar, byable(onecall) version 11, missing syntax newvarname = /exp [if] [in] [, MISSing] tempvar thetag n var tempfile `thedata' quietly { gen double `var' = `exp' `if' `in' if "`byvars'"=="" gen `n' = _n else by `byvars': gen `n' = _n save `thedata', replace keep `byvars' `var' egen `thetag' = tag(`byvars' `var') `if' `in', `missing' keep if `thetag' sort `byvars' `var' if "`byvars'"=="" gen `n' = _n else by `byvars': gen `n' = _n ren `var' `varlist' merge 1:1 `n' using(`thedata'), nogen } // Closes Quetly brace. end
Do you have suggestions how to achieve what I want in some simple way? Or alternatively, do you see any reason why my program is causing so much damage, and generally not doing what I want it to do?
0 Response to I am trying to make something like -levelsof- saving the levels of a variable, but not in a local, rather in a another variable.
Post a Comment