[R] appending data to a row

David Winsemius dwinsemius at comcast.net
Thu Feb 14 22:36:22 CET 2013


On Feb 14, 2013, at 1:07 PM, Jamie wrote:

> For an analysis of data from twins, I'd like to do some rearranging in my
> dataframe. Currently, each twin has his or her own row. I'd like to add
> several columns of the co-twin's data to each row. In other words, this is
> the current situation:
> 
> FamilyID  ParticipantID  IQ  Digit_span
> 1             1          95  6
> 1             2          93  7
> 2             3          102 8
> 2             4          101 9
> 3             5          106 7
> 3             6          108 9
> 
> And this is what I'd like to have, only with even more co-twin data:
> 
> FamilyID  ParticipantID  IQ  Digit_span Co-twin_IQ Co-twin_Digit_span
> 1             1          95  6          93          7
> 1             2          93  7          95          6
> 2             3          102 8          101         9
> 2             4          101 9          102         8
> 3             5          106 7          108         9
> 3             6          108 9          106         7
> 
> I'm not sure how to tell R to take the specified values from the other row
> with the same family ID and append them with a new name. Thanks for any
> ideas you can offer me.

> dat2 <- merge(dat, dat, by.x=1, by.y=1)
> dat2 [ with( dat2, ParticipantID.x != ParticipantID.y) , ]
   FamilyID ParticipantID.x IQ.x Digit_span.x ParticipantID.y IQ.y Digit_span.y
2         1               1   95            6               2   93            7
3         1               2   93            7               1   95            6
6         2               3  102            8               4  101            9
7         2               4  101            9               3  102            8
10        3               5  106            7               6  108            9
11        3               6  108            9               5  106            7

-- 

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list