Announcement

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

  • Relabelling variables with first row values

    Hi, Due to the labelling of an imported excel file (which included merged cells and sub-labelled variables) I've ended up with my first row of data containing variable names 1.1, 1.2, 1.3a, 1.3 b etc. and the variable names being the default A, B, C etc.

    I'm scratching my head for the simplest way of using the values from the first row as the variable names (I would subsequently remove the top row).

    All suggestions appreciated.
    Matt


  • #2
    Note that none of 1.1, 1.2, 1.3a can be variable names in Stata (see help varname).

    Having said that, one way of approaching this is to loop over all variables and obtaining their value in the first observation. The basic loop is

    Code:
    unab varlist : * // <- here go the variable names
    
    foreach var of loc varlist {
        local value1 = `"`var'[1]"'
        do_whatever_with_value1
    }
    Best
    Daniel

    Comment


    • #3
      Thank you for that - ahhh so if I'm not allowed those variable names it's not as straightforward as I thought and I might be better off renaming all manually then removing the whole row.

      Comment


      • #4
        Depends. One could use strtoname() to transform the values into valid names. An easy solution for numbered variable names could be

        Code:
        rename (*) (v#) , addnumber
        Best
        Daniel

        Comment


        • #5
          Here's a worked out example of what daniel was suggesting

          Code:
          clear
          input str50(A B C D)
          "1.1 this" "1.2 that" "1.3a stuff" "1.3 b" 
          "1" "2" "X" "4" 
          end
          
          unab varlist : *
          foreach v of local varlist {
              local value = `v'[1]
              local vname = strtoname(`"`value'"')
              rename `v' `vname'
              label var `vname' `"`value'"'
          }
          
          drop in 1
          destring *, replace
          list

          Comment


          • #6
            Thanks very much

            Comment

            Working...
            X