dimanche 7 février 2016

r: when to use if else loops vs. functions

Need your help to resolve a loop issue;

Example data:

data2 <- structure(list(a = c(101, 102, 103, 104, 105, 106, 107, 108,109,110), 
                         b = c(1,1,1,1,2,2,3,4,4,4),
                         c = c(4, 4, 4, 4, 2, 2, 1, 3,3,3)), 
          .Names = c("ID", "Band", "Group_qty"), row.names = c(NA, 10L), class = "data.frame")

Example desired output:

Output <- structure(list(a = c(101, 102, 103, 104, 105, 106, 107, 108, 109, 110), 
                          b = c(1,1,1,1,2,2,3,4,4,4),
                          c = c(4,4,4,4,2,2,1,3,3,3),
                          d = c(102,103,104,103,"Class B","Class B","Class A",109,110,109)), 
                     .Names = c("ID", "Band", "Group_qty","NewID"), row.names = c(NA, 10L), class = "data.frame")

Draft if else statement: Note: This doesn't work.

data2$NewID <- 
  for(i in 1:length(data2$ID))
  {
    ifelse(data2$[i,3] == 1, "Class A", ifelse(data2[i,3] == 2, "Class B", ifelse(data2[i,2] == data2[i+1,2], data2[i+1,1], data2[i-1,1])))
  }

Question:

How do I create a working loop or function that I can use with dplyr. Rules:

  1. If Group_qty = 1; Output = Class A

  2. If Group_qty = 2; Output = Class B

  3. Else, check to see if the Band match the Band of the next row.

    • IF YES, Output = The next row's ID
    • IF NO, Output = Previous row's ID
  4. Once we reach the last row of the loop - we will not have a row+1. In that case: Output = Previous row's ID.

  5. Can this be resolved using dplyr & mutate. If yes, would love to have that as a possible answer.

Thanks,

Aucun commentaire:

Enregistrer un commentaire