Generating a twin using -gen- and -clonevar-


You can create a “twin” of a variable using -gen- or -clonevar-. I usually create a new variable before making changes, for example before a -recode- command, so that I will not alter the original variable. But I used to doing this with the -gen- command. For example:

sysuse auto, clear
gen foreign_g = foreign
recode (0 = 2)

There is nothing wrong with using -gen-. It’s just that I found out that for this purpose, -clonevar- is better. -clonevar- generates an exact copy of the variable. It does not just copy the values of the original, but aslo retain the original variable’s labels, notes, storage type, etc. (see -help clonevar-).

The following example illustrates the difference between the two.

sysuse auto, clear
gen foreign_g = foreign
clonevar foreign_c = foreign
des foreign*

The commands above return:


Leave a Reply