Announcement

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

  • Transposing numeric data so that string variable becomes variable names

    I have a dataset that looks something like the below that comes from a spreadsheet:

    Code:
    clear
    input str24 v1 float(companyceo electedofficial companyseniorexecutive)
    "Company CEO"                0 1.56 2.02
    "Elected official"         .57    0  .35
    "Company senior executive" .98 2.42    0
    end
    I would like to transpose the data so that the values in v1 become the variable names and the current variable names become values in v1.

    The resulting data should therefore look like the below:

    Code:
    clear
    input str22 v1 float(companyceo electedofficial companyseniorexecutive)
    "companyceo"                0 .57  .98
    "electedofficial"        1.56   0 2.42
    "companyseniorexecutive" 2.02 .35    0
    end
    I've tried the xpose command, but the resulting dataset produces variable names that are v1, v2, v3 etc. My real dataset is large and it would be fiddly to rename the variables manually.

    From browsing previous Statalist posts, I think the solution will be to somehow save the contents of the string variable, and then apply that as the names of the variables, but I can't seem to make that work.

    I've tried the following:

    Code:
    forval i = 1/3 {
        local name`i'=v1[`i']
    }
    
    xpose, clear varname
    
    forval i = 1/3 {
        rename v`i' `name'`i'
    }
    But I get an error that suggests that I am trying to name v1 as the value "1" when I am in fact trying to rename it "companyceo" - i.e. the contents of v1, observation 1.

    Could someone help me see where I am going wrong here?

  • #2
    I think I've actually solved this actually. I couldn't get rename to work, but I've labelled the variables by the original string variable and then converted the labels to names using strtoname (following an old post from Nick Cox):

    Code:
    xpose, clear varname
    drop in 1/1
    
    forval i = 1/3 {
        local name`i'=_varname[`i']
        label var v`i' "`name`i''"
    }
    
    label var _varname varname 
    
    foreach v of var * {
        local lbl : var label `v'
        local lbl = strtoname("`lbl'")
        rename `v' `lbl'
    }

    It was crucially the format of this line that was tripping me up:
    Code:
     label var v`i' "`name`i''"
    If you write "`name'`i'" rather than the above, it will just use the sequential numbers 1-3 rather than the content of the label.
    However, if there is a more elegant way to do this, then I'm happy to hear it!

    Comment

    Working...
    X