-1

I am trying to sort through times in a table and I have to work with different time zones so it is a great pain. Essentially, I have this:

dateSort <- function(times, date){
  if (hour(times)>=16) {
    date = as.Date(date - 1)
    table$TimePart <<- as.POSIXct(paste(date, times, sep=" "), tz="America/Chicago")
  } else {
    table$TimePart <<- as.POSIXct(paste(date, times, sep=" "), tz="America/Chicago")
  }
  return(table$TimePart)
}

The table$TimePart date-times are all in "YMD-HMS" format. I'm not sure why this does not work as expected.

I want any date-time that has a time greater than 16:00:00 to become a day earlier.

deezydaisy
  • 21
  • 5
  • I don't understand your input. Are `times` and `date` substrings of `table$TimePart`? – Rui Barradas Apr 03 '18 at 14:43
  • Please [provide a reproducible example](https://stackoverflow.com/a/5963610/1412059). Also, why are you writing a function with side effects (using `<<-`)? You function as written can not work for vector input since `if` is not vectorized. – Roland Apr 03 '18 at 14:45
  • Sorry for unclear input. If anyone is interested, the error was due to me thinking that `-1` will subtract 1 day, whereas that is only one second. – deezydaisy Apr 03 '18 at 15:20

1 Answers1

0

You could use day(1) from the lubridate package with an ifelse().

So we can do

library(lubridate)

time1 <- seq(
     from = as.POSIXct("2018-1-1 0:00", tz = "America/Chicago"),
     to = as.POSIXct("2018-1-3 23:00", tz = "America/Chicago"),
     by = "hour"
   )  

time2 <- as.POSIXct(ifelse(hour(time1) > 16, # if hour is > 16
                time1 - days(1), # subtract 1 day
                time1 # else return origin date & time
                ), origin = "1970-01-01", tz = "America/Chicago")
Highland
  • 148
  • 1
  • 7