I want to assign day/night/dusk/dawn to times of detections from my telemetry data and followed the solutions suggested to this question on stackoverflow: Adding information on day/dusk/night/dawn for tracking data in R
This is my df with t_ being my date/time column (=time of detection) I want to assign day/night/dusk/dawn to:
str(data)
'data.frame': 843 obs. of 8 variables:
$ date : Date, format: "2021-08-08" "2021-08-08" ...
$ lat : int 66 66 66 66 66 66 66 66 66 66 ...
$ lon : int -23 -23 -23 -23 -23 -23 -23 -23 -23 -23 ...
$ id : int 56985 56985 56985 56985 56985 56985 56985 56985 56985 56985 ...
$ t_ : POSIXct, format: "2021-08-08 01:00:00" "2021-08-08 23:00:00" ...
$ Receiver.ID : int 302371 302371 302371 302372 302372 302372 302377 302372 302372 302376 ...
$ Position.in.fjord: chr "T1R1" "T1R1" "T1R1" "T1R3" ...
$ row_num : int 1 2 3 4 5 6 7 8 9 10 ...
I got the time for sunrise, sunset, night and nightEnd for each day of my study with getSunlightTimes
(suncalc).
Because this study is conducted partly during summernight (24h daylight) in 66°N, no "night" or "nightEnd" is given until 07 Sept
str(sun)
'data.frame': 843 obs. of 8 variables:
$ date : Date, format: "2021-08-08" "2021-08-08" ...
$ lat : int 66 66 66 66 66 66 66 66 66 66 ...
$ lon : int -23 -23 -23 -23 -23 -23 -23 -23 -23 -23 ...
$ sunrise : POSIXct, format: "2021-08-08 04:46:07" "2021-08-08 04:46:07" ...
$ sunset : POSIXct, format: "2021-08-08 22:31:48" "2021-08-08 22:31:48" ...
$ night : POSIXct, format: NA NA ...
$ nightEnd: POSIXct, format: NA NA ..
$ row_num : int 1 2 3 4 5 6 7 8 9 10 ...
Creating a new df with a column containing day/night/dusk/dawn:
daynight <-data %>%
full_join(sun, by="row_num") %>%
mutate(period= case_when(t_ %within% interval(sunset, night) ~ 'dusk',
t_ %within% interval(night, nightEnd) ~ 'night',
t_ %within% interval(nightEnd, sunrise) ~ 'dawn',
t_ %within% interval(sunrise, sunset) ~ 'day'))
Day, dusk and dawn are mostly assigned correctly to the date/time data from the detections. Mistakes occur close to the transition between intervals, i.e. when the time of detection (t_) is within one hour of the time when the next interval (sunrise, sunset,..) beginns. For example with t_ is one detection:
t_ / sunrise / sunset / period
2021-09-14 07:00:00 / 2021-09-14 06:50:36 / 2021-09-14 20:07:21 / dawn
"dawn" should be "day".
How can I assign day/night/dusk/dawn 100% correctly to my data?