有两个时间数据集:来自雨水收集器的数据-时间间隔ti
与start
,end
和雨水p
(每周期的雨水总量,单位为mm)< / p>
ti <- data.frame(
start = c("2017-06-05 19:30:00", "2017-06-06 12:00:00"),
end = c("2017-06-05 23:30:00", "2017-06-06 14:00:00"),
p = c(16.4, 4.4)
)
ti[,1] <- as.POSIXct(ti[, 1])
ti[,2] <- as.POSIXct(ti[, 2])
测量站的时间序列ts
和time
和参数q
,即排水量(立方米/秒)
ts <- data.frame(stringsAsFactors=FALSE,
time = c("2017-06-05 16:00:00", "2017-06-05 19:00:00",
"2017-06-05 21:00:00", "2017-06-05 23:00:00",
"2017-06-06 9:00:00", "2017-06-06 11:00:00", "2017-06-06 13:00:00",
"2017-06-06 16:00:00", "2017-06-06 17:00:00"),
q = c(0.78, 0.84, 0.9, 0.78, 0.78, 0.78, 0.78, 1.22, 1.25)
)
ts[,1] <- as.POSIXct(ts[,1])
我需要将时间序列与时间间隔相交,并在ts
中在TRUE/FALSE
中创建一个新列,如果该行在下雨间隔(TRUE
)中而不是({{1 }})就像这样:
FALSE
您对如何应用这种简单操作有任何想法吗?
答案 0 :(得分:2)
使用sqldf
:
library(sqldf)
sqldf('select ts.*, case when ti.p is not null then 1 else 0 end as rain
from ts
left join ti
on start <= time and
time <= end')
结果:
time q rain
1 2017-06-05 16:00:00 0.78 0
2 2017-06-05 19:00:00 0.84 0
3 2017-06-05 21:00:00 0.90 1
4 2017-06-05 23:00:00 0.78 1
5 2017-06-06 9:00:00 0.78 0
6 2017-06-06 11:00:00 0.78 0
7 2017-06-06 13:00:00 0.78 1
8 2017-06-06 16:00:00 1.22 0
9 2017-06-06 17:00:00 1.25 0