title: Encode a string variable in non-alphanumeric order
body: <p>I want to <code>encode</code> a string variable in such a way that assigned numerical codes respect the original order of string values (as shown when using <code>browse</code>).  Why? I need encoded variable labels to get the correct variable names when using <code>reshape wide</code>.</p>
  
  <p>Suppose <code>var</code> is a string variable with no labels:  </p>
  
  <pre><code>var      label(var)  
  "zoo"    none  
  "abc"    none
  </code></pre>
  
  <p>If you start with:</p>
  
  <blockquote>
    <p>encode var, gen(var2)</p>
  </blockquote>
  
  <p>the labels are 1="abc" 2="zoo" as can be seen with</p>
  
  <blockquote>
    <p>label li</p>
  </blockquote>
  
  <p>But I want <strong>the labels sorted as they come</strong>, as shown in <code>browse</code> for an unchanged order of variables later.</p>
  
  <p>I didn't find an <code>encode</code> option in which the labels are added in the order I see when using <code>browse</code>. </p>
  
  <p>My best idea is to do it by hand:  </p>
  
  <blockquote>
    <p>ssc install labutil<br>
    labvalch var, f(1 2) t(2 1) </p>
  </blockquote>
  
  <p>This is nice, but I have >50 list entries.</p>
  
  <p>Other approach:  When using <code>reshape</code> use another order, but I don't think that works. </p>
  
  <blockquote>
    <p>reshape wide x, i(id) j(var)  </p>
  </blockquote>
  
  <p>I only found</p>
  
  <blockquote>
    <p>ssc install labutil<br>
    labmask regioncode, values(region)    </p>
  </blockquote>
  
  <p>as some alternative to <code>encode</code> but I'm not able to cope with strings using <code>labmask</code>.</p>