Announcement

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

  • Moving values to another row if the value of two columns match

    Dear Statalist,

    I want to fill the missing values, if values of variable "d" is equal to "age". So, in the first row, I want to rellocate all of values in var dest to type into values/row "13" in variable d, and let the first row (d=12) missing because there is not matching values between d and age. In sum, i want to relocate all values if condition "age" equal to "d". What i should to do for this situations?

    initial dataset
    id d age dest type
    1 12 13 mountain primer
    1 13
    1 14
    2 12
    2 13
    2 14 12 beach secondary
    desired dataset
    id d age dest type
    1 12
    1 13 13 mountain primer
    1 14
    2 12 12 beach secondary
    2 13
    2 14

    Thank you in advance

  • #2
    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input byte(id d age) str8 dest str9 type
    1 12 13 "mountain" "primer"  
    1 13  . ""         ""        
    1 14  . ""         ""        
    2 12  . ""         ""        
    2 13  . ""         ""        
    2 14 12 "beach"    "secondary"
    end
    
    foreach var in age dest type{
        bys id (`var'): replace `var'= cond(!missing(`var'[1]), `var'[1], `var'[_N]) 
        cap replace `var'=. if age!=d
        cap replace `var'="" if age!=d
    }
    Res.:

    Code:
    . sort id d
    
    
    . l, sepby(id)
    
         +--------------------------------------+
         | id    d   age       dest        type |
         |--------------------------------------|
      1. |  1   12     .                        |
      2. |  1   13    13   mountain      primer |
      3. |  1   14     .                        |
         |--------------------------------------|
      4. |  2   12    12      beach   secondary |
      5. |  2   13     .                        |
      6. |  2   14     .                        |
         +--------------------------------------+
    Last edited by Andrew Musau; 09 Nov 2022, 05:30.

    Comment


    • #3
      Thank you for your kind response Mr. Andrew...How if I want to move the values of the variables dest and type to the row with the same d and age too? So in i id1 d=13 contains age=13, dest=mountain, and type=primer

      Comment


      • #4
        See edit.

        Comment


        • #5
          Excellent...its work...thank you very much Mr. Andrew Musau

          Comment

          Working...
          X