Announcement

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

  • Combine and cumulate two variables

    Hi statalisters,

    I am writing in the forum for the first time but you had been helpful many many times.
    I have to distinct variables for the duration (years) of marriage and cohabitation (mdur and cdur) and I want to generate a new variable with the total of the two (total).

    Code:
               id    mdur    cdur   total
                1      .       1     1
                1      .       2     2
                1      1       .     3
                1      2       .     4
                2      .       4     4
                2      1       .     5
                2      2       .     6
                3      1       .     1
                3      2       .     2
                3      3       .     3


  • #2
    Welcome to Statalist.

    It seems to me the following accomplishes what you want, at least for the sample data you show.
    Code:
    * Example generated by -dataex-. To install: ssc install dataex
    clear
    input byte(id mdur cdur total)
    1 . 1 1
    1 . 2 2
    1 1 . 3
    1 2 . 4
    2 . 4 4
    2 1 . 5
    2 2 . 6
    3 1 . 1
    3 2 . 2
    3 3 . 3
    end
    generate seq = _n
    generate ctot = 0
    generate mtot = 0
    bysort id (seq): replace ctot = cond(cdur==.,ctot[_n-1],cdur)
    bysort id (seq): replace mtot = cond(mdur==.,mtot[_n-1],mdur)
    bysort id (seq): generate total2 = cond(ctot==.,0,ctot)+cond(mtot==.,0,mtot)
    list, sepby(id)
    Code:
         +-------------------------------------------------------+
         | id   mdur   cdur   total   seq   ctot   mtot   total2 |
         |-------------------------------------------------------|
      1. |  1      .      1       1     1      1      .        1 |
      2. |  1      .      2       2     2      2      .        2 |
      3. |  1      1      .       3     3      2      1        3 |
      4. |  1      2      .       4     4      2      2        4 |
         |-------------------------------------------------------|
      5. |  2      .      4       4     5      4      .        4 |
      6. |  2      1      .       5     6      4      1        5 |
      7. |  2      2      .       6     7      4      2        6 |
         |-------------------------------------------------------|
      8. |  3      1      .       1     8      .      1        1 |
      9. |  3      2      .       2     9      .      2        2 |
     10. |  3      3      .       3    10      .      3        3 |
         +-------------------------------------------------------+

    Comment


    • #3
      Thank you for the helpful response, William.

      Comment

      Working...
      X