Announcement

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

  • Foreach loops and forvalues loops

    Hi everyone,
    I am very new to Stata and I have to use foreach loops and forvalues loops for the first time. For an assignment, I basically have to find the mean values for average test scores in four different grades from kindergarten to grade3 depending on three different classroom types: small, regular, regular+aide and if the individuals were in the STAR project. It does not matter if the same participant was not in the STAR project in another grade. The variables are as follows:
    • Avgtestk Avgtest1 Avgtest2 Avgtest3 (average test scores from kindergarten to grade 3, 999=.)
    • ctypek ctype1 ctype2 ctype3 (class type assigned, 1=small, 2=regular, 3=regular with aide, 9=.)
    • stark star1 star2 star3 (part of the STAR project, 1=yes, 2=no, 9=.)
    I have already cleaned the data and all the missing values are denoted by "." in the instructions it says I can use a forvalues and foreach double loop to get all these means in three lines of code. Can anyone tell me how you would code this double loop? I have tried several ways, but can't seem to make it work.

    Thank you in advance, Alec.

  • #2
    Please see #4 at https://www.statalist.org/forums/help#adviceextras for our policy on questions about assignments.

    Comment


    • #3
      Since you were specifically asked in your assignment to use a double loop to solve this problem, you will need to use that approach. And since it is an assignment, I'm not going to show you how to do that here. You will need to figure it out, or consult with a teaching assistant.

      But, since you are learning Stata, I should point out that this problem should not be approached with a double loop, nor any loop at all. Rather, the data set should be reshaped to long, and then a single line command can calculate all of the means requested:

      Code:
      gen long obs_no = _n
      reshape long Avgtest ctype star, i(obs_no) j(grade) string
      by grade ctype, sort: egen mean_test_score = mean(Avgtest)

      Comment


      • #4
        Alternatively, it's also possible to get those statistics from a -table- command:

        Code:
        sysuse auto, clear
        table rep78 foreign, stat(mean mpg) nformat(%5.2f)

        Comment

        Working...
        X