Search code examples
rnested-if

How should I use nested ifelse statements?


I have created a data frame with the following data

name <- c("A","B","C","D","E","F","G","H","I","J")
age <- c(22,43,12,17,29,5,51,56,9,44)
sex <- c("M","F","M","M","M","F","F","M","F","F")
rock <- data.frame(name,age,sex,stringsAsFactors = TRUE)
rock

Now I want to find out:

If the name is E to J and sex is not equal to F then the status is "1F", if the name is A to D and age is greater than 15 then the status is "Young". Everything else is "Others"

so for that, i am applying following code:

rock$status <- ifelse(rock$name==c("E","F","G","H","I","J")& 
rock$sex!="F","1F",            
ifelse(rock$name==c("E","F","G","H","I","J")&rock$sex=="F","Fenamle",
ifelse(rock$name==c("A","B","C","D") & rock$age>15,"Young","Others")))
rock

But i am getting the output like:

  name  age    sex    status
1     A   22     M   Young   
2     B   43     F   Young   
3     C   12     M  Others  
4     D   17     M  Young   
5     E   29     M  Others  
6     F    5     F  Others  
7     G   51     F  Others  
8     H   56     M  Others 
9     I    9     F  Others  
10    J   44     F  Others  

But, it has to be "1F" on E and H.but it is showing "Others"

What wrong have I done into my code?

Please correct me and also give me some valuable suggestions regarding this.


Solution

  • We need to use %in% instead of ==:

    rock$status <- ifelse(rock$name %in% c("E", "F", "G", "H", "I", "J") & 
                            rock$sex != "F", "1F",            
                          ifelse(rock$name %in% c("E", "F", "G", "H", "I", "J") & 
                                   rock$sex == "F", "Female",
                                 ifelse(rock$name %in% c("A", "B", "C", "D") &
                                          rock$age > 15, "Young", "Others")))
    rock
    
    #    name age sex  status
    # 1     A  22   M   Young
    # 2     B  43   F   Young
    # 3     C  12   M  Others
    # 4     D  17   M   Young
    # 5     E  29   M      1F
    # 6     F   5   F  Female
    # 7     G  51   F  Female
    # 8     H  56   M      1F
    # 9     I   9   F  Female
    # 10    J  44   F  Female