Announcement

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

  • import data when varnames are numeric

    Hello,

    I am dealing with a large umber of .txt files with this format:

    id rname 1980 1981 1982 1983
    1 region1 0.2 0.3 0.15 0.17
    2 region2 0.1 0.25 0.13 0.11
    3 region3 0.01 0.21 0.24 0.13

    (note: years and regions might not be regular for all the files, this is just a made up sample).


    Ideally, I would like the import into Stata to look like:

    id rname y1980 y1981 y1982 y1983
    1 region1 0.2 0.3 0.15 0.17
    2 region2 0.1 0.25 0.13 0.11
    3 region3 0.01 0.21 0.24 0.13

    so that the first row is directly imported as variable names and then reshaping long to obtain the panel format.
    Any suggestion on how to proceed?

    Thank you, Alberto

  • #2
    Stata stores the numeric variable names as value labels as they are not legal names. So something along the lines of the following achieves what you want.

    Code:
    import delimited myfile.txt, delimiter(space) varnames(1)
    foreach var of varlist v*{
        rename `var' y`:var lab `var''
    }

    Comment


    • #3
      Thank you Andrew, very useful
      I followed that and came up with this, which works too (an extra step because I had to remove blanks from labels)

      foreach var of varlist v* {
      local x : variable label `var'
      local x : subinstr local x " " "", all
      rename `var' y`x'
      }

      This does not work however, when I have multiple variables (in some of the files, I realize only now) with blank labels
      *example*
      1980 1981 1982 1983
      1 region1 0.2 0.3 0.15 0.17
      2 region2 0.1 0.25 0.13 0.11
      3 region3 0.01 0.21 0.24 0.13

      so the program gets stuck because there is already a variable renamed 'y'.
      Any hint will be very welcome, best, Alberto

      Comment


      • #4
        Just add an -if- exclusion:

        Code:
        foreach var of varlist v*{
            if !missing("`:var lab `var''"){
                rename `var' y`:var lab `var''
            }
        }

        Comment

        Working...
        X