Announcement

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

  • create a sequence of locals with the variable labels

    Hello Statalist,
    I would need to have a local named varlabel1 containing the label of the first variable in the dataset, a local varlabel2 containing the label ofthe second variable 2 and so on.
    I am using the following code:

    Code:
    sysuse auto, replace
    local varlabels
    ds
        foreach v in `r(varlist)'{
        local varlabel : var l `v'
        local varlabels `varlabels' "`varlabel'"
        }
    local n_columns `c(k)'
        forval i=1/`n_columns' {
            local varlabel`i' `: word `i' of `varlabels''
        }
    mac list
    It works properly, but for the fact that it messes up with the first variable label, which is not recorded within double quotes in the local varlabels. Because of that,
    Code:
    local varlabel`i' `: word `i' of `varlabels''
    consider "Make and Model" (the label of the first variable) as three different words.

    Can anyone see why is that and how I could possibly fix the problem?
    Many thanks in advance,
    G.

  • #2
    Code:
    sysuse auto, clear 
    local varlabels
    
    foreach v of var *  {
        local varlabel : var l `v'
        local varlabels `"`varlabels' "`varlabel'" "' 
    }
    
    forval i=1/`c(k)' {
        local varlabel`i' `: word `i' of  `varlabels''
    }
    
    mac list

    Comment


    • #3
      Well, I don't know why Make and Model doesn't get wrapped in quotes the way it should, nor do I see a way to fix it. But really there's a simpler approach to your goal. Your local macro varlabels is simply not needed anyway. Just create varlabel1, varlabel2, etc. directly.

      Code:
      sysuse auto, replace
      
      local i = 1
      ds
      foreach v of varlist `r(varlist)' {
          local varlabel`i': var label `v'
          local ++i
      }
      macro list
      Note: Crossed with Nick's #2, which solves both problems.

      Comment


      • #4
        many thanks, both answers were extremely useful and to the point!

        Comment

        Working...
        X