Skip to content
Prev 343203 / 398513 Next

data.table/ifelse conditional new variable question

Perhaps I am missing something but I do not get the same result:

x <- read.table(textConnection("Family.ID Sample.ID Relationship
2702  349       mother
2702  3456  sibling
2702  9980  sibling
3064  3  father
3064  4  mother
3064  5    sibling
3064  86   sibling
3064  87   sibling"), header = TRUE)
closeAllConnections()

xs <- with(x, split(x, Family.ID))
res <- do.call(rbind, lapply(xs, function(l){
 l$PID <- l$MID <- 0
father <- with(l, Relationship == 'father')
 mother <- with(l, Relationship == 'mother')
 if(sum(father) == 0)
l$PID[l$Relationship == 'sibling'] <- 0
 else l$PID[l$Relationship == 'sibling'] <- l$Sample.ID[father]
 if(sum(mother) == 0)
l$MID[l$Relationship == 'sibling'] <- 0
 else l$MID[l$Relationship == 'sibling'] <- l$Sample.ID[mother]
 l
}))
 #Family.ID Sample.ID Relationship MID PID
#2702.1      2702       349       mother   0   0
#2702.2      2702      3456      sibling 349   0
#2702.3      2702      9980      sibling 349   0
#3064.4      3064         3       father   0   0
#3064.5      3064         4       mother   0   0
#3064.6      3064         5      sibling   4   3
#3064.7      3064        86      sibling   4   3
#3064.8      3064        87      sibling   4   3

HTH,
Jorge.-




On Sun, Aug 17, 2014 at 11:47 AM, Kate Ignatius <kate.ignatius at gmail.com>
wrote: