Announcement

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

  • sum of each variable in var list

    Hello,

    I would like to know how to generate a variable that sums all of each variable in the loop. For example,

    I want to make a variable GPcost_year1 = GP_E7_C24 + GP_E8_C29 + GP_E9_C36 + GP_E10_C42

    I used this code but it doesn't work.
    foreach x of varlist GP_E7_C24 GP_E8_C29 GP_E9_C36 GP_E10_C42 {
    egen GPcost_year1 = total(`x')
    }
    Many thanks in advance.

    Kim

  • #2
    I guess you want

    Code:
    gen double wanted = GP_E7_C24  + GP_E8_C29 + GP_E9_C36  + GP_E10_C42
    No loop is needed for that. That gives a total over observations (rows) and if you want the total of that variable, or each of the components, the easiest commands are probably tabstat and table.

    Comment


    • #3
      I wasn't sure whether you wanted the sum by rows only, or whether you to take the summed rows and total the column.

      I'm new to stata - this might not be the most elegant but I think it works:

      Makes variable row_sums that sums all the rows from the variables listed:
      Code:
      egen row_sums=rowtotal(GP_E7_C24 GP_E8_C29 GP_E9_C36 GP_E10_C42)
      Makes a variable which totals the just generated row_sums:
      Code:
      egen total_of_row_sum=total(rowsum)

      Comment


      • #4
        I do not know about elegance, but the -egen, rowtotal()- that William proposed above is the easiest here, because it accepts wild cards, so you do not need to spell out the names of the variables explicitly.

        If you want to do this with a loop, then something like this:

        Code:
        gen myrowsum = 0
        foreach x of varlist GP_E7_C24 GP_E8_C29 GP_E9_C36 GP_E10_C42 {
        replace myrowsum = myrowsum + `x'
        }

        Comment


        • #5
          You also need to think what you want to happen when one or more of your variables are missing. The proposed solutions above act differently in the face of missing values. In Stata

          Code:
          . dis 7 + .
          .
          that is, if you are adding a missing to 7, the result will be missing.

          On the other hand -egen, rowtotal()- treats missing values as 0, so in the sum above 7 + . rowtotal() will give you 7.

          Comment


          • #6
            Dear all,

            Thank you for all of your replies. Nick, William, and Joro all of your replies were really useful. Nick is right as I needed to generate the variable. But, I wanted to do this in a loop to simplify the process as I should repeat the same thing 100 times with different variables.

            Thanks again for your help.

            Kind regards,
            Kim

            Comment

            Working...
            X