[R] if else statement in loop

Kate Ignatius kate.ignatius at gmail.com
Sun Sep 28 21:13:43 CEST 2014


I have two data frames

For simplicity:

X=

V1 V2 V3  V4 V5 V6
samas4 samas5 samas6 samas4_father samas5_mother samas6_sibling
samas4 samas5 samas6 samas4_father samas5_mother samas6_sibling
samas4 samas5 samas6 samas4_father samas5_mother samas6_sibling

Y=

FID IID
FAM01 samas4
FAM01 samas5
FAM01 samas6

I want to set to create a new IID in Y using V4 V5 V6 in X using an
ifelse statement in a loop.  I've used something like the following
(after figuring out my factor problem):

for(i in length(1:(2*nrow(X)))){
    Y$IID1new <- ifelse((as.character(Y[,2]) == as.characterXl[,i]) &
X$IID1new != '') , as.character(as.matrix(X[,(2*nrow(X)+i)])),'')
}

But of course this tends to overwrite.

Is there an easy way to set up a loop to replace missing values? This
didn't work either but not sure if its as easy as this:

Y$IID1new <- ifelse((as.character(Y[,2]) == as.characterXl[,i]) &
X$IID1new != '') , as.character(as.matrix(X[,(2*nrow(X)+i)])),'')

for(i in length(2:(2*nrow(X)))){
ifelse((as.character(Y[,i]) == as.character(Xl[,i])),
X[is.na(X$IID1new)] <- as.character(as.matrix(X[(2*nrow(X)+i)])),'')
}

Thanks!

K.



More information about the R-help mailing list