任何人都可以帮忙,我有一个数据框(set_rise),每行包含当天的日落时间和第二天的日出时间.我有第二个数据框(数据),其中包含一列日期/时间.我想在数据中创建第二列,其中包含对应于白天或黑夜的字母,方法是获取数据中的日期/时间,并检查它是否在set_rise中的任何时间之间.
#df1- sunset, sunrise times
set_rise
set rise
1 2013-03-01 18:28:00 2013-03-02 08:27:00
2 2013-03-02 18:31:00 2013-03-03 08:23:00
3 2013-03-03 18:35:00 2013-03-04 08:19:00
4 2013-03-04 18:38:00 2013-03-05 08:15:00
5 2013-03-05 18:42:00 2013-03-06 08:12:00
6 2013-03-06 18:45:00 2013-03-07 08:08:00
#df2 my data
timedate
1 2013-03-01 19:00:00
2 2013-03-03 10:00:00
3 2013-03-06 00:01:00
我想这样输出
data
timedate night_day
2013-03-01 19:00:00 N
2013-03-03 10:00:00 D
2013-03-06 00:01:00 N
输出输出(set_rise)
dput(set_rise)
structure(list(set = structure(list(sec = 0, min = 28L, hour = 18L,
mday = 1L, mon = 2L, year = 113L, wday = 5L, yday = 59L,
isdst = 0L, zone = "WET", gmtoff = NA_integer_), .Names = c("sec",
"min", "hour", "mday", "mon", "year", "wday", "yday", "isdst",
"zone", "gmtoff"), class = c("POSIXlt", "POSIXt")), rise = structure(list(
sec = 0, min = 27L, hour = 8L, mday = 2L, mon = 2L, year = 113L,
wday = 6L, yday = 60L, isdst = 0L, zone = "WET", gmtoff = NA_integer_), .Names = c("sec",
"min", "hour", "mday", "mon", "year", "wday", "yday", "isdst",
"zone", "gmtoff"), class = c("POSIXlt", "POSIXt")), night = "N"), .Names = c("set",
"rise", "night"), row.names = 1L, class = "data.frame")
输出(数据)的输出
dput(data)
structure(list(timedate = structure(c(1362873600, 1362960000,
1364342400), class = c("POSIXct", "POSIXt"))), .Names = "timedate", row.names = c(NA,
-3L), class = "data.frame")
最佳答案 这需要一些准备,但速度非常快.首先,将set_rise转换为POSIXct(而不是POSIXlt).接下来,将日期转换为数字并组合所有值,以便它们形成日夜交替的值.然后,调用findInterval告诉您每个数据日期的间隔:如果间隔是奇数,那么它是夜晚,否则是天.所以:
#convert to POSIXct
set_rise[]<-lapply(set_rise,as.POSIXct)
#combine all the numeric values together
intervals<-c(t(matrix(c(as.numeric(set_rise$set),as.numeric(set_rise$rise)),ncol=2)))
#call findInterval and set the values, checking the parity
c("D","N")[1+(findInterval(as.numeric(data$timedate),intervals) %% 2)]
#[1] "N" "D" "N"