Bruh
Bruh

Reputation: 285

If statements to fulfill conditions relating to dates

I'm trying to manipulate the data with these dates.

Condition: if start time and end time overlaps with previous date from 21:00 to 9:00 next day, then the correct date would be the previous date.

For example here: Obs 3: the start time 12/5/2020 9:27 and end time 12/5/2020 12:13 overlaps with 12/4/2020 21:00 to 12/5/2020 10:00. So the correct date should be 12/04/2020. enter image description here

With this logic, the next step is to combine hrs_slept for example Obs 6 and 7 because they have the same dates, which would become:

Condition: for each ID, if there are same dates, hrs_slept need to be combined: enter image description here

original:

start_time <- c("2020-12-02 23:01:00","2020-12-04 04:17:00","2020-12-05 09:27:00","2020-12-06 06:38:00","2020-12-06 11:42:00","2020-12-08 01:22:00","2020-12-08 05:33:00", "2020-12-08 16:59:00","2020-12-09 03:15:00")
end_time <- c("2020-12-03 01:03:00","2020-12-04 09:42:00","2020-12-05 12:13:00","2020-12-06 09:16:00","2020-12-06 14:50:00","2020-12-08 04:24:00","2020-12-08 06:37:00","2020-12-08 18:05:00","2020-12-09 06:21:00")
hrs_sleep <- c(2.03,5.42,2.77,2.63,3.13,3.03,1.07,1.10,3.10)
a <- data.frame(start_time,end_time,hrs_sleep)%>%
  mutate(ID=104)
a$start <- as.POSIXct(a$start)
a$end <- as.POSIXct(a$end)

Desired:

start_date <- c("2020-12-02","2020-12-03","2020-12-04","2020-12-05","2020-12-06","2020-12-07","2020-12-08")
hrs_sleep_new <- c(2.03,5.42,2.77,2.63,3.13,4.10,4.20)
b <- data.frame(start_date,hrs_sleep_new)%>%
  mutate(ID=104)
b$start_date <- as.POSIXct(b$start_date)

I hope I made the logic clear. Essentially, I just need some sort of if statements for the two conditions written in bold. And I have a lot more observations with different IDs so these conditions need to be for each ID.

I appreciate all the help there is! Thanks!!!

Upvotes: 0

Views: 53

Answers (1)

Lucas
Lucas

Reputation: 322

Sorry, but I'm not sure I understand the conditions. However, try this code:

a <- a %>% mutate(start_date = as.Date(ifelse(hour(start) < 10, date(start)-1,date(start)), origin = "1970-01-01")) # Create the dates

a %>% group_by(ID, start_date) %>% summarise(hrs_sleep_new = sum(hrs_sleep)) # Sum the sleep hours

Upvotes: 1

Related Questions