Announcement

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

  • Putting same label values to Several Variables with 'foreach' loop.

    Greetings, Stata Lovers!


    label define outcome 0 "No" 1 "Yes".


    I have several variables, e.g., var1 to var25.

    I want to attach the same labels (outcome) to all these variables.

    Right now, I have to individually label each variable using the following command:

    label value var1 outcome.
    label value var2 outcome.
    label value var3 outcome.
    label value var4 outcome.
    label value var5 outcome.

    and so on....


    Is there an easier way of doing it? Maybe using the 'foreach' loops.


    Regards

    Stata Beginner.







  • #2
    Details matter here. If the variables are ordered and there are no other variables in between, take the name of the first and last variables and

    Code:
    foreach var of varlist var1-var25{
        label values `var' outcome
    }
    See

    Code:
    help varlist
    If the variables are literally named "var1", "var2", ...,

    Code:
    forval i=1/25{
        label values var`i' outcome
    }
    Otherwise, specify the full list (pseudo code below)

    Code:
    foreach var in var1 var2 var3 var4 ... var25{
         label values `var' outcome
    }

    Comment


    • #3
      Actually, the syntax is

      Assign value label to variables

      label values varlist lblname [, nofix]
      So the command allows a variable list. No loop is needed then.

      Code:
      label values var1-var25 outcome
      or

      Code:
      label values var* outcome
      and so on.

      Comment

      Working...
      X