JD69
JD69

Reputation: 3

How can I alter the date of a datetime vector depending on the time with lubridate?

I am trying to manipulate a date inside a datetime vector depending on time of day.

Each item in the vector newmagic looks something like this "2020-03-05 02:03:54 UTC" For all the items that have a time between 19:00 and 23:59 I want to go back one day.

I tried writing an if statement:

if(hour(newmagic)>=19&hour(newmagic)<=23){
  date(newmagic)<-date(newmagic)-1
}

giving me no output but

Warning message: In if (hour(newmagic) >= 19 & hour(newmagic) <= 23) { : the condition has length > 1 and only the first element will be used

when I limit the data to the condition and simply execute date()-1

newmagic[hour(newmagic)>=19&hour(newmagic)<=23&!is.na(newmagic)] <- date(newmagic[hour(newmagic)>=19&hour(newmagic)<=23&!is.na(newmagic)])-1

The output does remove 1 day but also sets the time to 0 Original:

"2020-03-07 20:58:00 UTC"

After date()-1

"2020-03-06 00:00:00 UTC"

I don't really know how to go on. How can I adapt the if statement so that it will actually do what I intend to? How can I rewrite the limitation in the second approach so that the time itself will stay intact?

Thank you for the help

Upvotes: 0

Views: 48

Answers (1)

Sri Sreshtan
Sri Sreshtan

Reputation: 545

You can try out this in your original data set. I have used lubridate and tidyverse package. Initially I have split the data frame into date and time. Then I have converted the variables into date and time format and used the ifelse condition.

The code and the output is as follows:-

library(tidyverse)
library(lubridate)
ab <- data.frame(ymd_hms(c("2000-11-01 2:23:15", "2028-03-25 20:47:51",
                           "1990-05-14 22:45:30")))
colnames(ab) <- paste(c("Date_time"))
ab <- ab %>% separate(Date_time, into = c("Date", "Time"), 
                sep = " ", remove = FALSE)
ab$Date <- as.Date(ab$Date)
ab$Time <- hms(ab$Time)
ab$date_condition <- ifelse(hour(ab$Time) %in% c(19,20,21,22,23),
                            ab$date_condition <- ab$Date -1,
                            ab$date_condition <- ab$Date)       
ab$date_condition <- as.Date(ab$date_condition, format = "%Y-%m-%d", 
                             origin = "1970-01-01")
ab




#           Date_time       Date        Time date_condition
1 2000-11-01 02:23:15 2000-11-01  2H 23M 15S     2000-11-01
2 2028-03-25 20:47:51 2028-03-25 20H 47M 51S     2028-03-24
3 1990-05-14 22:45:30 1990-05-14 22H 45M 30S     1990-05-13

Upvotes: 1

Related Questions