Announcement

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

  • Replacing values of Multiple variables with foreach loop

    Hi Everyone.


    I am trying to change the value of several variables at once using the 'foreach' command. Following is the syntax I am using and getting the following errors


    . foreach varlist 'q1a - q1v' {
    2. replace 'var' = runiformint(1,3) if totaldrugs >=3
    3.
    . }
    invalid syntax
    r(198);


    . foreach var in varlist 'q1a - q1v' {
    2. replace 'var' = runiformint(1,3) if totaldrugs >=3
    3.
    . }
    ' invalid name
    r(198);



    . foreach var in varlist q1a - q1v {
    2. replace var = runiformint(1,3) if totaldrugs >=3
    3.
    . }
    variable var not found
    r(111);


    I am not able to figure out the where am I making the mistake?








  • #2
    If you use -foreach var in-, you have to specify the full list. See

    Code:
    help foreach


    Code:
    foreach var of varlist q1a-q1v{
        replace `var'= runiformint(1,3) if totaldrugs>=3
    }
    Last edited by Andrew Musau; 05 Feb 2024, 03:29.

    Comment


    • #3
      Originally posted by Andrew Musau View Post
      If you use -foreach var in-, you have to specify the full list. See

      Code:
      help foreach


      Code:
      foreach var of varlist q1a-q1v{
      replace `var'= runiformint(1,3) if totaldrugs>=3
      }


      Thank you Andrew..

      The code worked.

      Comment

      Working...
      X