Announcement

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

  • Copying information from one row to another

    I have a set of matched observations. I want to copy the values of some variables from one matched row to another. How can I do it?

    Code:
    * Example generated    by -dataex-. To install:    ssc    install    dataex
    clear
    input float(groupid    amount num) str3 federal
    131 42.2 1 "yes"
    131    . . ""   
    132 56.1 3 "yes"
    132    . . ""   
    133 39.9 3 "no"
    133    . . ""   
    134 55.6 2 "yes"
    134    . . ""   
    135 44.4 1 "yes"
    135    . . ""   
    end
    Thanks.

  • #2
    I am assuming that there are other variables with (possibly) differing values within each pair, so that you aren't just duplicating observations.

    Code:
    clear
    input float(groupid    amount num) str3 federal
    131 42.2 1 "yes"
    131    . . ""  
    132 56.1 3 "yes"
    132    . . ""  
    133 39.9 3 "no"
    133    . . ""  
    134 55.6 2 "yes"
    134    . . ""  
    135 44.4 1 "yes"
    135    . . ""  
    end
    
    foreach v in amount num federal {
    bysort groupid : replace `v' = `v'[3 - _n] if missing(`v') & _N == 2
    }
    
    list, sepby(groupid)
    For your data example, you could write simpler code that would work. I am using a more abstract and general trick that is worth knowing and will catch some instances where the data are not quite so tidy.

    If you have paired observations then within groups 3 - _n is 2 when observation number _n is 1 and 1 when observation number _n is 2. So, the subscript points to the other observation in the pair. The constraint that _N should be 2 should do no harm.

    See also https://journals.sagepub.com/doi/pdf...867X0800800414 from 2008.
    Last edited by Nick Cox; 05 Sep 2023, 04:45.

    Comment


    • #3
      Thanks so much Nick.

      Comment

      Working...
      X