【发布时间】:2021-05-31 08:24:17
【问题描述】:
我有一个数据集,其中包含几个月的日期时间、纬度和经度变量的跟踪数据,如下所示:
> start <- as.POSIXct("2018-08-01 00:00:00", format="%Y-%m-%d %H:%M:%S", tz="UTC")
> datetime <- seq(from = start, length.out = 2880, by = "5 mins")
> lat<-rep(seq(from=50, to= 30, length.out = 10), each=288)
> lon<-rep(seq(from=110, to= 70, length.out = 10), each=288)
> data<-cbind.data.frame(datetime, lat, lon)
> head(data)
datetime lat lon
1 2018-08-01 00:00:00 50 110
2 2018-08-01 00:05:00 50 110
3 2018-08-01 00:10:00 50 110
4 2018-08-01 00:15:00 50 110
5 2018-08-01 00:20:00 50 110
6 2018-08-01 00:25:00 50 110
我想根据来自getSunlightTimes 的信息添加一个新列,其中包含有关一天中的时间段的信息,即白天、黄昏、夜晚或黎明:
> data$date<-as.Date(data$datetime)
> sun<-getSunlightTimes(data=data, tz="UTC", keep=c("sunrise","sunset","night","nightEnd"))
> head(sun)
date lat lon sunrise sunset night
1 2018-08-01 50 110 2018-07-31 21:09:50 2018-08-01 12:25:18 2018-08-01 15:01:56
2 2018-08-01 50 110 2018-07-31 21:09:50 2018-08-01 12:25:18 2018-08-01 15:01:56
3 2018-08-01 50 110 2018-07-31 21:09:50 2018-08-01 12:25:18 2018-08-01 15:01:56
4 2018-08-01 50 110 2018-07-31 21:09:50 2018-08-01 12:25:18 2018-08-01 15:01:56
5 2018-08-01 50 110 2018-07-31 21:09:50 2018-08-01 12:25:18 2018-08-01 15:01:56
6 2018-08-01 50 110 2018-07-31 21:09:50 2018-08-01 12:25:18 2018-08-01 15:01:56
nightEnd
1 2018-07-31 18:33:13
2 2018-07-31 18:33:13
3 2018-07-31 18:33:13
4 2018-07-31 18:33:13
5 2018-07-31 18:33:13
6 2018-07-31 18:33:13
所以黄昏对应于sunset和night之间的datetime值,nightEnd和sunrise之间的黎明,sunrise和sunset之间的白天和night和nightEnd之间的夜晚.
我试过了:
> data$period<-rep(" ", length.out=nrow(data))
> data$period[which(data$datetime>sun$sunrise & data$datetime<sun$sunset)]<-"day"
> data$period[which(data$datetime>sun$sunset & data$datetime<sun$night)]<-"dusk"
> data$period[which(data$datetime>sun$nightEnd & data$datetime<sun$sunrise)]<-"dawn"
> data$period[which(data$period==" ")]<-"night"
但这会在几天之间的转换中引起问题。有人有什么建议吗?
亲切的问候
【问题讨论】:
-
请让 SO 用户知道解决方案是否有效。如果它们不起作用,也许我们可以修复它们。
标签: r date datetime posixct date-sunrise