Reputation: 1
In my dataset I have a parameter called visit_datetime. This parameter determines during which period the participant visited the researcher. This can be at any time a day. I want to give a value "1" if the visit was between 08.00 and 20.00, and value "2" if the visit was between 20.00 and 08.00. Is there an easy way to do this? For all other date/time calculations I use the package lubridate. The visit_datetime is parsed the right way, because other calculations do work.
I tried it like this:
tijd_presentatie = ifelse(visit_datetime > hm("08:00") & visit_datetime < hm("20:00"), 1, 2)
But this gives me always the value of "2".
Upvotes: 0
Views: 24
Reputation: 17204
Using lubridate::hour()
:
library(lubridate)
visit_datetime <- seq(ymd_hms("2023-02-14 00:00:00"), by = "hour", length.out = 24)
tijd_presentatie <- ifelse(hour(visit_datetime) >= 8 & hour(visit_datetime) < 20, 1, 0)
data.frame(visit_datetime, tijd_presentatie)
visit_datetime tijd_presentatie
1 2023-02-14 00:00:00 0
2 2023-02-14 01:00:00 0
3 2023-02-14 02:00:00 0
4 2023-02-14 03:00:00 0
5 2023-02-14 04:00:00 0
6 2023-02-14 05:00:00 0
7 2023-02-14 06:00:00 0
8 2023-02-14 07:00:00 0
9 2023-02-14 08:00:00 1
10 2023-02-14 09:00:00 1
11 2023-02-14 10:00:00 1
12 2023-02-14 11:00:00 1
13 2023-02-14 12:00:00 1
14 2023-02-14 13:00:00 1
15 2023-02-14 14:00:00 1
16 2023-02-14 15:00:00 1
17 2023-02-14 16:00:00 1
18 2023-02-14 17:00:00 1
19 2023-02-14 18:00:00 1
20 2023-02-14 19:00:00 1
21 2023-02-14 20:00:00 0
22 2023-02-14 21:00:00 0
23 2023-02-14 22:00:00 0
24 2023-02-14 23:00:00 0
Upvotes: 2