-1

I am trying to categorize shifts based on the end time of a shift in R. In order to this I am using constraints for different time intervals, but I don't know how to specify them in a constraint. I already tried "" and as.POSIXct, but both did not work.

This is the code I am using:

> for (i in 1:length(SHIFTS2)){
  if (SHIFTS2$ENDTIME > 10:00:00 && SHIFTS2$ENDTIME <= 18:00:00){
    SHIFTS2$ENDCAT[i] <- 1
  }else if (SHIFTS2$ENDTIME > 18:00:00 && SHIFTS2$ENDTIME <= 02:00:00){
    SHIFTS2$ENDCAT[i] <- 2
  }else{
    SHIFTS2$ENDCAT[i] <- 3
  }
}

Hope someone can help me out!

  • I guess `SHIFTS2` is a dataframe? If so, you forgot to add the index within the if (else if) statements e.g. `SHIFTS2$ENDTIME[i]`. I guess you getting error which states that only first element of `SHIFTS2$ENDTIME` can be compared. However, please provide more info about your data. – Tobias May 07 '18 at 09:04
  • @Tobias Yes, SHIFTS2 is my dataframe and SHIFTS2$ENDTIME is a column where times are stored in the format hms. I added the index, but I still get the same error. Do you have any idea what it could be? – user9684814 May 07 '18 at 09:34
  • Please provide some example data (as stated [here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)) and also the error you receive. – Tobias May 07 '18 at 09:54
  • What datatype is the column `ENDTIME`? Is it character? We definitely need more information about your data. – Tobias May 07 '18 at 10:01

1 Answers1

0

Here is an example how it would work if your ENDTIME-column is defined as character.

start <- c("08:00:00", "16:00:00", "17:00:00", "19:00:00", "12:00:00", "06:00:00", "23:00:00")
end <- c("14:00:00", "23:00:00", "22:00:00", "01:00:00", "18:00:00", "12:00:00", "04:00:00")

SHIFTS2 <- data.frame(as.character(start), as.character(end))
SHIFTS2$ENDCAT <- ""

colnames(SHIFTS2)[1:2] <- c("STARTTIME", "ENDTIME")

for (i in 1:nrow(SHIFTS2)){
  endtime <- as.numeric(substring(SHIFTS2$ENDTIME[i], first = 1, last = 2))
  if (endtime > 10 && endtime <= 18){
    SHIFTS2$ENDCAT[i] <- 1
  }else if ((endtime > 18 && endtime <= 23) || (endtime >= 0 && endtime <= 2)) {
    SHIFTS2$ENDCAT[i] <- 2
  }else{
    SHIFTS2$ENDCAT[i] <- 3
  }
}
Tobias
  • 564
  • 3
  • 13