Announcement

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

  • foreach with multiple varlists

    Hi Statalist members,

    I am comparing data on responses to thirty test questions ("variable") to the correct answers to those questions ("a_variable"). I want to generate a new variable that tells me whether the response is correct, incorrect, or missing ("r_variable").

    In other words, I want to run this code for thirty variables (one varlist) against thirty response variables (another varlist):
    gen r_variable=1 if variable==a_variable
    replace r_variable=0 if variable!=a_variable
    replace r_variable=. if variable>;=99
    (My codes for "missing" or "incomplete" are values 99 and higher, so I have no missing values in my original variables.)

    I searched previous posts but couldn't figure out how to apply responses to my data and variables.

    I am using Stata 11.2.

    Thank you very much!

    Best,
    Corinna

  • #2
    I'm not sure if I understand you correctly, but my first guess is to put your code in a -foreach var in ... - loop. Where the ... need to be replaced with the names of your variables (without the stubs r_ etc.). Then, you can replace variable with `var' in your code.

    Comment


    • #3
      Hello Corinna,

      Welcome to Statalist! For future posts, its helpful if you present your code within CODE delimiters -- it makes it easier to read. See http://www.statalist.org/forums/help#stata for more info.

      Try this code:
      Code:
      foreach var of varlist VARIABLES { //VARIABLES = the varlist of your responses
          gen r_`var' = `var'==a_`var'
          replace r_`var' = . if `var'>=99
      }
      In the above code, I assume that you have consistency in naming of variables. That is, if your response variable is named "question1", then your correct answer variable is named "a_question1".
      Last edited by Roger Chu; 24 Mar 2017, 08:41. Reason: Crossed with Sebastian's. Essentially the same advice.

      Comment

      Working...
      X