Announcement

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

  • Looping over two sections of a variable name

    I want to loop through and add the totals for two variables (boys and girls), for each grade and each group.

    This is an example variable in my dataset: c1obcg. The 'c1' part refers to the grade and ranges from c1 to c12. The 'obc' part refers to a group and there are five groups of this type: sc, st, gen, obc, and tot. The 'g' part refers to girls and is replaced by b for boys in other variable names. So, in all, there are 120 variables, which I am trying to combine into 60 variables.

    This is the invalid code I wrote after reading other posts, but it doesn't work. So, could you please help me with this?

    local x "sc st gen obc tot"
    local n: word count `x'
    forvalues i=1/12 {
    forvalues j=1/`n' {
    egen g`i'`j' = rowtotal(c`i'`j'g c`i'`j'b)
    }
    }

  • #2
    Consider this

    Code:
    forvalues i=1/12 {
        foreach x in sc st gen obc tot {
            di "g`i'`x' is total of c`i'`x'g c`i'`x'b"
            * egen g`i'`x' = rowtotal(c`i'`x'g c`i'`x'b)
            * why not gen g`i'`x' = c`i'`x'g + c`i'`x'b ???
        }
    }

    Comment


    • #3
      Worked perfectly. Thank you!

      Also, I chose egen because there are girls-only and boys-only schools. So, I didn't want a missing value in one variable to make the total missing. Is this logic correct? If not, please let me know.

      Comment


      • #4
        You're right that egen, rowtotal() ignores missings and addition does not. There are ways around that, such as replace the missings by zeros any way or by working with

        Code:
         
         gen g`i'`x' = max(c`i'`x'g, 0) + max(c`i'`x'b, 0)
        It may be surprising that zero is returned as the maximum of zero and missing, but the principle "ignore missings when possible" here overrides "missing is arbitrarily large".

        Code:
        . di max(0, .)
        0

        Comment


        • #5
          That's interesting! Thank you!

          Comment

          Working...
          X