How to add timeslots per date in a df in R

Viewed 76

I want to generate a dateframe that has a range of dates and times. In the first column I want the date, and the second should have the times per date (from 08:00 to 17:00)

I've started by creating a dates df like this:

data <- seq(as.Date("2020-08-10"), by = "day", length.out = 10)
df <- data.frame(data, place1 = 0, place2 = 0)

Now I want to add want to add 10 time-rows per date (08:00 to 17:00). I was thinking about doing it with an apply function, but I can't seem to figure it out.

So basically I want the dataframe to look like this:

Date       |     Time     |     Place1     |   Place 2
20-08-10   |     08:00    |      0         |     0
20-08-10   |     09:00    |      0         |     0
....
20-08-10   |     16:00    |      0         |     0
20-08-10   |     17:00    |      0         |     0
21-08-10   |     08:00    |      0         |     0
21-08-10   |     09:00    |      0         |     0
....

Thanks in advance!

1 Answers

using expand.grid.

dat <- expand.grid(date=data, time=sprintf("%02d:00", 8:17))
dat <- dat[order(dat$date), ]

dat[1:12, ]
#          date  time
# 1  2020-08-10 08:00
# 11 2020-08-10 09:00
# 21 2020-08-10 10:00
# 31 2020-08-10 11:00
# 41 2020-08-10 12:00
# 51 2020-08-10 13:00
# 61 2020-08-10 14:00
# 71 2020-08-10 15:00
# 81 2020-08-10 16:00
# 91 2020-08-10 17:00
# 2  2020-08-11 08:00
# 12 2020-08-11 09:00

however, as @Allan Cameron already pointed out in comments, it's probably better to use as.POSIX format which combines date and time:

dates <- as.POSIXct(seq(0, 60^2*24*10, 60^2), origin="2020-08-10")
dates <- dates[as.numeric(strftime(dates, "%H")) %in% 7:17]
head(dates, 13)
# [1] "2020-08-10 07:00:00 CEST" "2020-08-10 08:00:00 CEST"
# [3] "2020-08-10 09:00:00 CEST" "2020-08-10 10:00:00 CEST"
# [5] "2020-08-10 11:00:00 CEST" "2020-08-10 12:00:00 CEST"
# [7] "2020-08-10 13:00:00 CEST" "2020-08-10 14:00:00 CEST"
# [9] "2020-08-10 15:00:00 CEST" "2020-08-10 16:00:00 CEST"
# [11] "2020-08-10 17:00:00 CEST" "2020-08-11 07:00:00 CEST"
# [13] "2020-08-11 08:00:00 CEST"
Related