Announcement

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

  • Labeling variables with a for loop

    I have a bunch of serially placed variables: Q49_1_a-Q49_104_h. I am trying to label them such that the labels become something like the following:

    Apple_Total_harvested
    Apple_Total_consumed
    Orange_Total_harvested
    Orange_Total_consumed
    Mango_Total_harvested
    Mango_total_consumed

    I have a lot more fruits and attributes for which I want to use the for loop to save my time. I have tried the following code which produced an "invalid syntax r(198)" error.

    Code:
    local fruits yam tomato beet onion pepper cabbage papaya carrot lettuce cassava beans maize others
    local attributes Total_harvested Consumed Sold Bartered Stored Stored_in_PHC Lost_Due_to_Pest_or_During_Storage Others
    
    unab vlist: Q49_1_a-Q49_104_h
    
    local i=1
    foreach f of local fruits {
        foreach a of local attributes {
            local var: word `i' of `vlist'
            label `var' "'f'_`a'"
            local ++i
        }
    }
    Any help will be highly appreciated.
    Last edited by Taz Raihan; 21 Sep 2018, 13:49.

  • #2
    There are two syntax errors in the command -label `var' "'f'_`a'"- It should be:

    Code:
    label var `var' "`f'_`a'"
    Coding tip: It's asking for trouble to, on the one hand, take advantage of Stata's syntax abbreviation, saying -label var- for -label variable- and to also use var as the name of a local macro in a loop over variables. It's legal, of course, and it can be done correctly. But it really is a setup to make the mistake shown above; and it's a hard mistake to find because your eye tends not to see the difference between `var' (wrong) and var `var' (correct, in this context) easily.

    My habit, just a personal preference, is to usually use single letter names for the local macros that are either loop indices or represent elements of a list that is being iterated over. So, I would have used v instead of var as the name of this local macro, both in the command that had the errors and in the -local- command that created it. Single letter names stand out more easily when you are looking at your code. I particularly try to avoid macro names that look like variable names, Stata commands, or other syntactic features of Stata (such as -var- which is an accepted abbreviation of -variable- in the -label variable- command.) Again, just a personal habit and preference, but I think it really does reduce the frequency of errors.
    Last edited by Clyde Schechter; 21 Sep 2018, 14:33.

    Comment


    • #3
      Clyde Schechter thank you so much, sir, for your time. I will keep your advice in mind.

      Comment

      Working...
      X