Announcement

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

  • foreach rename loop keeps stopping after one loop due to variable no longer in varlist

    I am writing a foreach loop to iterate over each variable, use its label as the new variable name, and add part of a string from its first row as the ending of its name. I.e. suppose the data looks like so:
    A B C
    Dog Dog Cat
    12 15 30
    And suppose the labels for A, B, and C are 2015, 2016, and 2017, respectively. Then the output I would like is:
    2015_D 2016_D 2017_C
    Dog Dog Cat
    12 15 30
    The following loop seems to work one by one:


    Code:
    foreach var of varlist * {
        if substr(`var'[1], 1, 1) == "D" {
            rename `var' `: var label `var''_D
        }
        if substr(`var'[1], 1, 1) == "C" {
            rename `var' `: var label `var''_C
        }
    }
    The issue I am running into is that this generally stops after each iteration and states. For instance, if I was to run it from the start on the tables above, I would get:

    Code:
    A not found
    It seems like this is suggesting that it can't continue the loop because one of the variables was renamed and is therefore no longer in the varlist. Although, I don't see why the varlist would not update with each iteration. I tried putting this loop into another loop in order to simply repeat it many times (since it does work one by one). Any suggestions would be greatly appreciated!
    Last edited by Carl Isaac; 01 Oct 2020, 09:19.

  • #2
    I will repeat again the advice I gave you in your previous post. Stata variable names cannot begin with numbers.

    foreach var of varlist * {
    if substr(`var'[1], 1, 1) == "D" {
    rename `var' `: var label `var''_D
    }
    if substr(`var'[1], 1, 1) == "C" {
    rename `var' `: var label `var''_C
    }
    }
    Once you address the point above, there is no need to specify multiple conditions if your rule is that the variable name should be the label + underscore + first letter of the word in the first observation.

    Comment


    • #3
      It is most probably what Andrew says.

      If not, and in the future, provide a data sample using -dataex-, so that we can try what we have in mind.

      Comment


      • #4
        Let me add to the advice above that while you write

        this generally stops after each iteration
        in fact it is stopping in the middle of an iteration, because (in your example) having successfully renamed A to something new, the second if command no longer can find A[1] to compare the first character to "C". Changing the second if to else if would solve this problem in your example code.

        Comment

        Working...
        X