Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Reshape wide to long without variable prefix

    Hello!

    I have data that looks something like this (466 observations, 489 variables):

    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input float Date double(eq aamulehtiiideadmerger679144)
     9831       . .
     9862       . .
     9893  9.0202 .
     9921  8.7175 .
     9952  8.7781 .
     9982  8.8144 .
    10013 10.4853 57
    10043 10.1099 57
    10074 11.2723 81
    10105 12.3498 101
    10135 11.4891 94
    10166 10.8288 86
    10196  9.9044 90
    10227    8.98 83.9
    10258   9.112 69
    10287  9.3762 86
    10318 10.4326 85
    10348 10.5647 .
    10379  8.5838 .
    10409   9.112 .
    10440  8.7159 .
    10471  6.6029 .
    10501  7.3293 .
    10532  7.5273 .
    end
    format %td Date

    What's noteworthy is that the variable names do not have common prefixes, and that some variable names are the maximum length allowed by Stata (32 chars), which makes adding a prefix not as simple.

    I'd like to reshape the data from this wide format to a long format with id being Date, a variable for company (all other columns currently), and a variable for price.

    How should I do this properly?

  • #2
    If you haven't got a common prefix you just need to supply one.

    Code:
    ds Date, not
    
    rename (`r(varlist)')  y=
    
    reshape long y, i(Date) j(Which) string

    As you say, some variable names are already at the limit of 32 characters, in which case you will need to shorten them first. Here is a way to find such names


    Code:
    foreach v of varlist * {
         if strlen("`v'") == 32 local bad `bad' `v'
    }
    
    di "`bad'"

    Comment


    • #3
      Thanks for the assistance Nick - your code worked perfectly!

      For anyone wondering about truncating the variable names, this worked for me:

      Code:
      // Truncate all variable names over 30 characters.
      foreach v of varlist * {
           if strlen("`v'") > 30 {
               local v_trunc = substr("`v'", 1, 29)
              rename `v' `v_trunc'
           }
      }
      If there's a better way to do this, feel free to improve!

      Comment


      • #4
        That's in the right spirit and you could add the new prefix within the loop.

        Comment

        Working...
        X