'Complex Data Manipulation in R
I am facing a subject and I really need your help,
I have daily transports by location:
location = c("a1", "a2", "a3").
For location = a1, I have for example, for a time range of 0h00 to 01h59 :
transport = c("2021-01-05 00:05:08", "2021-01-05 00:05:42", "2021-01-05 00:37:07", "2021-01-05 00:46:12", "2021-01-05 00:58:55", "2021-01-05 01:09:58", "2021-01-05 01:24:49", 2021-01-05 01:43:58", "2021-01-05 01:50:57")
I would like to get the following result: if vehicle 1 leaves at "2021-01-05 00:05:08", it will be available only 1 hour later and therefore it will be able to do the transport available just after "2021-01-05 01:09:58" and the tgg value for both will be 0.5 and so on for vehicule 2, vehicule 3...., the final goal being to avoid as much as possible 1 vehicle by transport while respecting the time range, i.e. no vehicle will be able to do a transport if its availability is beyond 01h59.
My script looks like this but I can't get it right in the example above :
Base <- structure(list(location = c("a1", "a1", "a1", "a1", "a1", "a1",
"a1", "a1", "a1"), transport = structure(c(1609805108, 1609805142,
1609807027, 1609808335, 1609809889, 1609811457, 1609807572, 1609808998,
1609811038), class = c("POSIXct", "POSIXt"), tzone = "UTC"),
date = structure(c(18632, 18632, 18632, 18632, 18632, 18632,
18632, 18632, 18632), class = "Date"), `time slot` = c(2,
2, 2, 2, 2, 2, 2, 2, 2), hour = c(0L, 0L, 0L, 0L, 1L, 1L,
0L, 1L, 1L), tesss = structure(c(1609805108, 1609805142,
1609807027, 1609808335, 1609809889, 1609811457, 1609807572,
1609808998, 1609811038), class = c("POSIXct", "POSIXt"), tzone = "UTC")), row.names = c(NA,
-9L), class = c("data.table", "data.frame"))
Base %>%
group_by(location, date, `time slot`) %>%
mutate(avail := transport + hm("1.0"),
jk := avail,
tgg := case_when((jk < max(transport , na.rm = T) & (max(tess) - min(tess) >= hm("1.0"))) ~ 0.5,
length(date) == 1 ~ 1,
TRUE ~ 1)) %>%
mutate(jk := case_when(transport == max(transport , na.rm = T) ~ min(jk, na.rm = T),
transport != max(transport , na.rm = T) ~ jk),
tgg := case_when((jk <= min(jk, na.rm = T) & length(date) > 1 & jk < max(transport , na.rm = T) | is.na(transport )) ~ 0.5,
length(date) == 1 ~ 1,
TRUE ~ 1)
) %>%
mutate(day:= case_when((transport != min(transport , na.rm = T) & transport != max(transport , na.rm = T)) ~ transport ,
transport == min(transport , na.rm = T) ~ as_datetime(NA),
transport == max(transport , na.rm = T) ~ as_datetime(NA)),
avail := transport + hm("1.0"),
tgg := case_when(length(date) == 1 ~ 1,
(max(tess) - (tess) >= hm("1.0")) ~ 0.5,
TRUE ~ tgg)) -> b1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
