Announcement

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

  • Collapse two variables, but still want to see some of the other variables in the dataset

    Hi,

    I want to collapse two variables, but I still want to see the other variables.
    I have data for many transactions that is identified with a receiptID. I want to see the totalsum of the receipt, and therefor want to collapse following:

    collapse (sum) transactions, by (receipt_id)

    At the moment I just have all the transactions in one receipt_id but I want to see the receipt as one. I also have variables with gender, age and storename that I want to see together with the collapse, but I dont know how to do this.

    collapse (sum) transactions (?) gender (?) storename (?) age , by (receipt_id)

    I want the gender, storename and age to stay the same so I can compare the different receipts by also these variables. I don“t know what I can put in the ( ) for the variables to not change.

    Can anyone help me?

  • #2
    Silje:
    I'm not sure whether I got it right, but you may want to try:
    Code:
    collapse (sum) transactions (mean) gender storename age, by (receipt_id)
    Kind regards,
    Carlo
    (Stata 19.0)

    Comment


    • #3
      You can also use egen directly:

      Code:
      bysort receipt_id: egen totalSum = total(transactions)
      bysort receipt_id: drop if _n != 1

      Comment


      • #4
        You can't have it both ways. If you leave out gender, you won't keep the details on gender. Other way round, if you add gender to the by() call, you'll get finer aggregation. Same point for other variables.

        Comment


        • #5
          Sounds like what you want to do is

          Code:
          egen total_trans = total(transactions), by(receipt_id)
          This keeps all the data and adds the sum of the transactions as a new variable. In contrast, collapse changes the unit of analysis and would require dropping the other variables.

          Comment

          Working...
          X