Stata The Stata listserver
[Date Prev][Date Next][Thread Prev][Thread Next][Date index][Thread index]

st: Copy string variable as value label

From   Friedrich Huebler <>
Subject   st: Copy string variable as value label
Date   Mon, 25 Apr 2005 07:27:19 -0700 (PDT)

When a string variable is converted to a numeric variable with
-encode-, the numeric values follow the sort order of the string
variable. I would like to -encode- a string variable based on the
sort order of another variable. My original data is like this:

var   mean
a     1.5
b     1.2
b     1.2
b     1.2
c     1.8
c     1.8

I would like to create the variable "newvar" like this, using the
sort order of the variable "mean":

var   mean   newvar   (label for newvar)
b     1.2    1        b
b     1.2    1        b
b     1.2    1        b
a     1.5    2        a
c     1.8    3        c
c     1.8    3        c

My solution is shown below. Creating "newvar" itself is simple but
there must be a better way to assign the labels.

sort mean
egen newvar = group(mean)
lab def newvar 1 "temp"
levels(newvar), local(levels)
foreach l of local levels {
  gen temp = ""
  replace temp = var if newvar==`l'
  levels(temp), local(templabel)
  lab def newvar `l' `templabel', modify
  drop temp
lab val newvar newvar

How can this code be improved? Thank you for your suggestions.

Friedrich Huebler

Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
*   For searches and help try:

© Copyright 1996–2017 StataCorp LLC   |   Terms of use   |   Privacy   |   Contact us   |   What's new   |   Site index