1

I used ifelse to filter my working result, what I want to do is like below,

when the j equals to A or B or C, and k equals to first, then rbind in var15.

when the j equals to D or E, and k equals to second, then do rbind in var30.

when the j equals to F, then rbind in var45.

How can I revise my code to achieve what I need?

# Below is what I've done. 

  for (j in c("A","B","C","D","E","F")){
    for (k in c("first","second")){

      # do something here.

      ifelse(j== "A" | "B" | "C" & k== "first", var15<-rbind(var1, var2),var15<-rbind(var15,var1, var2))
      ifelse(j== "D" | "E" & k== "second", var30<-rbind(var3,var4,var5),var30<-rbind(var30,var3,var4,var5))
      ifelse(j== "F" , var45<-rbind(var3,var4),var45<-rbind(var45,var3,var4))

      }

    Get_all <- rbind(Get_all ,var15,var30,var45)

    }
MlolM
  • 247
  • 4
  • 12
  • Membership in a set is tested like `j %in% c("A","B")`. Also, you should probably use `var15 <- if (cond) x else y`. Also, you should not grow things in a loop in R (a google search will lead to resources that explain why). – Frank Mar 20 '17 at 15:43
  • It needs to be either `j %in% c("A", "B", "C")` or `j == "A" | j == "B" | j == "C"` – manotheshark Mar 20 '17 at 15:43

1 Answers1

1

%in% will uses the lhs to match with rhs. Since the length of lhs is equal to 1 in your for loop, it will always evaluate to a logical of length one.

Then compare k with first or second. Since lhs and rhs are of equal length which is one, in comparing k with first or second, == will evaluate to a logical of length one. Then you combine both logicals with && condition.

for (j in c("A","B","C","D","E","F")){
  for (k in c("first","second")){

    # do something here.

    var15 <- ifelse( ( j %in% c( "A", "B", "C") && k == "first"), rbind(var1, var2), rbind(var15, var1, var2))
    var30 <- ifelse( ( j %in% c( "D", "E") && k == "second"), rbind(var3, var4, var5), rbind(var30, var3, var4, var5))
    var45 <- ifelse( j == "F" , rbind( var3, var4), rbind(var45, var3, var4))

  }

  Get_all <- do.call( 'rbind', list( var15,var30,var45))

}
Sathish
  • 12,453
  • 3
  • 41
  • 59