Home > front end >  Nested if statement within for loop
Nested if statement within for loop

Time:10-25

I need to fix this if statement nested in a for loop.

Create Column: GroupAllFemalesBoysLived
This column looks at all ticket numbers that have the same value and then returns a 1 if all females (women and children) and all boys (male children) survived within that group (all ticket numbers are the same), else returns a 0.

for (loopitem in titanic1$Ticket) {
    if (titanic1$Gender == "Male Child" & titanic1$Survived == 1 && 
        titanic1$Gender == "Female Child" & titanic1$Survived == 1 && 
        titanic1$Gender == "Female Adult" & titanic1$Survived == 1) 
        {titanic1$GroupAllFemalesBoysLived = 1} 
    else {titanic1$GroupAllFemalesBoysLived = 0}
}

I am getting this error message:

Warning message in if (titanic1$Gender == "Male Child" & titanic1$Survived == 1 && : “the condition has length > 1 and only the first element will be used”

CodePudding user response:

There's no need for a loop, R is vectorized.

cond1 <- titanic1$Survived == 1
cond2 <- titanic1$Gender %in% c("Male Child", "Female Child","Female Adult")
titanic1$GroupAllFemalesBoysLived <- cond1 & cond2
  • Related