I have a data frame called result
which looks like that.
lat | lng | Night |
---|---|---|
41.60701 | 1.000831 | 2019-06-19 |
41.98151 | 1.973059 | 2020-04-11 |
... | ... | ... |
Basically, I whoul add 4 columns. One column for the time of sun set, the second for the sun rise, the third for the duration of the night in hour and finally the fourth for the sampling effort (I juste add the time buff to the duration of the night). I managed to do this by using a loop in the following code (unsing suncalc package for the getSunlightTimes
).
library("plyr")
library("dplyr")
library("reshape")
library("data.table")
library("stringr")
library("tidyr")
library("ineq")
library("suncalc")
library(suncalc)
time_buff <- 0.30
posta <- ls()
sorti <- ls()
night_hours <- ls()
temp <- result
for (i in 1:dim(temp)[1]) {
lat <- temp$lat[i]
long <- temp$lng[i]
sset <- as.Date(temp$Night[i])
sris <- sset + 1
Tsset <- getSunlightTimes(sset, lat, long,
keep = c("sunrise", "sunset"), tz = "UTC"
)$sunset
Tsris <- getSunlightTimes(sris, lat, long,
keep = c("sunrise", "sunset"), tz = "UTC"
)$sunrise
posta[i] <- Tsset
sorti[i] <- Tsris
night_hours[i] <- round(as.numeric(Tsris - Tsset), 2)
}
# fetch results
temp$sun_set <- as.POSIXct(as.numeric(unlist(posta)),
origin = "1970-01-01", tz = "UTC"
)
temp$sun_rise <- as.POSIXct(as.numeric(unlist(sorti)),
origin = "1970-01-01", tz = "UTC"
)
temp$night_hours <- as.numeric(unlist(night_hours))
temp$night_effort <- as.numeric(temp$night_hours) + (time_buff * 2)
result <- temp
But it take very long time to run. So, I would know if there is an other simplest way to do that, using for example the mutate function from dplyr package instead of using a loop ?