[R] appending data to a row
arun
smartpink111 at yahoo.com
Thu Feb 14 22:41:11 CET 2013
HI,
May be this helps:
(assuming that there are only twins)
dat1<- read.table(text="
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
",sep="",header=TRUE)
dat1$Co_twin_IQ<-NA
dat1$Co_twin_Digit_span<-NA
dat1[,5:6]<-do.call(rbind,lapply(split(dat1,dat1$FamilyID),function(x)x[2:1,3:4]))
dat1
# FamilyID ParticipantID IQ Digit_span Co_twin_IQ Co_twin_Digit_span
#1 1 1 95 6 93 7
#2 1 2 93 7 95 6
#3 2 3 102 8 101 9
#4 2 4 101 9 102 8
#5 3 5 106 7 108 9
#6 3 6 108 9 106 7
dat2<- read.table(text="
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
",sep="",header=TRUE)
colnames(dat2)<- colnames(dat1)
identical(dat1,dat2)
#[1] TRUE
A.K.
----- Original Message -----
From: Jamie <jms2cor4 at gmail.com>
To: r-help at r-project.org
Cc:
Sent: Thursday, February 14, 2013 4:07 PM
Subject: [R] appending data to a row
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.
Jamie in Illinois
[[alternative HTML version deleted]]
______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
More information about the R-help
mailing list