Announcement

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

  • Numlist in foreach loop, when number is within variable name

    I have been trying to use ‘numlist’ in a foreach loop as I have a list of about 100 variables, all repeated 8 times (as if in a longitudinal study) and the only difference in each variable name is the numbers 1 to 8.

    Example variables:
    v1_msg v2_msg v3_msg v4_msg v5_msg v6_msg v7_msg v8_msg
    v1_age v2_age v3_age v4_age v5_age v6_age v7_age v8_age

    And I’m using the code:

    foreach num in numlist 1 2:8 {
    tab v`num'_msg, m
    tab v`num'_age, m
    }

    I got the error r(111) "variable vnumlist_msg not found"

    I then added a display command first to see if my loop was even working:
    foreach num in numlist 1 2:8 {
    di `num'
    tab v`num'_msg, m
    tab v`num'_age, m
    }

    And I got the error r(111) "numlist not found"

    My question is, is this possible with this command? And if not - how can I achieve this outcome without repeatedly typing each variable name 8 times. I also want to do more then just tabulate each variable in foreach.

    I have also tried using variable wild cards such as:
    tab v*_msg
    tab v#_msg
    These also gives me the errors: r(103) "too many variables specified" and then r(111) "v ambiguous abbreviation" (respectively).

    Thank you for your help!
    Victoria

  • #2
    Sure but you need

    Code:
    foreach num of numlist 1 2:8
    for your approach to work. See the help to see that keywords in and of split the syntax into two flavors.

    FWIW I would tend to write

    Code:
    forval j=1/8 {
    and have a personal rule that j loops over variables, but no one has to agree with the latter, and caprice sometimes wins.

    Comment


    • #3
      On the second question you should try tab1 as tabulate otherwise thinks that you are asking for a single table which surely won’t work for many variables.

      Comment


      • #4
        Thank you Nick!!

        Comment

        Working...
        X