mardi 4 février 2020

if_else using each element of a conditional vector individually

I am writing an R program that uses user defined functions to create objects to clean/manipulate our raw data. One of the tasks I am asking of the program is to recode (effectively switch) some portion of a variable based on a date and a set of id's.

set.seed(14)

date_switch2 <- as.POSIXct("2018-10-30")
maze_switch2 <- c(2,4)

test <-  data.frame(id = c(rep(1,4),rep(2,3), rep(3,8), rep(4,5)),
                    date = sort(rep(seq.Date(as.Date("2018-10-29"), as.Date("2018-11-01"),1),
                                    each = 20), decreasing = F),
                    x = sort(x= round(runif(20,0, 10), 2), decreasing = F),
                    ant = sample(c("n", "s"), replace = T, size = 20))

Using this example data I would like to recode/switch ant on date == "2018-10-30" for id == c(2,4) such that n becomes s and s becomes n. The user of the program is asked which if any dates ant needs to be switched and if yes, for which id. This is done using

d <- readline(prompt = "Did antenna orientation change during study (y/n): ")

  if(d == "y"){
    date_switch2 <- readline(prompt = "On what date did antenna orientation change?: ")
    maze_switch2 <- readline(prompt = "which mazes did antennae change orientation?: ")
  }

I have tried using if_else() but that didn't work as intended because maze_switch2 contains two elements, thus only working properly half the time.

if(d == "y") { 
     test$ant2 <- dplyr::if_else(test$date >= date_switch2 & test$id == maze_switch2 & as.character(test$ant) == "s", "n", 
                                dplyr::if_else(test$date >= date_switch2 & test$id == maze_switch2 & as.character(test$ant)== "n", "s", 
                                               as.character(test$ant)))  

} else {
  test$ant2 <- test$ant
}

I suppose I could make each element separate objects. In this example that would double the amount of code for this task and not by dynamic with the user defined function nor scaleable. This solution needs to be dynamic and scaleable. I have no idea what the user will input.

My latest attempt was to loop through maze_switch2; but it results in NA's for all records (i.e. all id's) >= the date of interest.

if(d == "y") { 
  for(i in maze_switch2) {
  test$ant2 <- dplyr::if_else(test$date >= date_switch2 & test$id == maze_switch[i] & as.character(test$ant) == "s", "n", 
              dplyr::if_else(test$date >= switch & test$id == maze_switch[i] & as.character(test$ant)== "n", "s", 
                                  as.character(test$ant)))  
}
  } else {
  test$ant2 <- test$ant
}

Thanks for the help!

Aucun commentaire:

Enregistrer un commentaire