R-如何计算data.frame中日期间隔的总和



我想计算可变时间间隔的洪水总和。该期间的结束是在向量或数据中给出的。G。4天6天。

如何创建一个灵活的代码,以便我可以计算不同的date_end并创建具有不同时间长度的向量?

我的完整data.frame包含大约2年,还有12个末端日期和3个不同的时期lenght。

df <- data.frame(date = c("2016-11-01", "2016-11-02", "2016-11-03", "2016-11-04", "2016-11-05", "2016-11-06", "2016-11-07", "2016-11-08", "2016-11-09", "2016-11-10"),
           flooded = c(0,0,0,1,1,1,0,0,1,1))
date_end <- as.Date(c("2016-11-04", "2016-11-10"), "%Y-%m-%d")
##lenght of time period, e. g. 4 days
period <- c(4,6)
   date             flooded
1  2016-11-01       0
2  2016-11-02       0
3  2016-11-03       0
4  2016-11-04       1
5  2016-11-05       1
6  2016-11-06       1
7  2016-11-07       0
8  2016-11-08       0
9  2016-11-09       1
10 2016-11-10       1

总的来说,我想计算我的obersavtion点的洪水。谢谢

您可以编写一个计算序列的函数。

floodCount <- function(datecol, floodcol, e, p) {
  e <- as.Date(e)
  datecol <- as.Date(datecol)
  stopifnot(!anyNA(c(e, p)))
  stopifnot((e - p) %in% datecol)
  return(sum(floodcol[which((datecol == e - p + 1)):which(datecol == e)]))
}

在您的示例数据上使用:

with(df, floodCount(date, flooded, date_end[2], period[2]))
# [1] 4

在更大的规模上(请参见下面的数据(:

with(df2, floodCount(date, flooded, date.end2[8], period2[3]))
# [1] 2

或手动

with(df2, floodCount(date, flooded, "2015-11-06", 8))  # oops...
with(df2, floodCount(date, flooded, "2016-11-06", 8))  # oops...
with(df2, floodCount(date, flooded, "2016-11-06", 4))  # ok!
# [1] 3

更新

要计算所有日期和周期的所有组合,您可以Vectorize floodCount,然后在向量的序列上使用outer(),并包裹在`dimnames<-`()中。

floodCountv <- Vectorize(function(x, y) 
  with(df2, floodCount(date, flooded, date.end2[x], period2[y])))
`dimnames<-`(outer(seq_along(date.end2), seq(period2), floodCountv),
         list(as.character(date.end2), period2))
#            4 6 9
# 2017-02-11 2 4 6
# 2017-02-22 3 4 7
# 2017-03-13 4 5 7
# 2017-07-22 2 4 6
# 2017-07-24 2 3 6
# 2017-08-02 2 3 5
# 2017-09-08 1 1 3
# 2017-10-07 1 2 3
# 2018-04-16 1 2 4
# 2018-04-27 3 5 5
# 2018-10-08 3 4 6
# 2018-10-23 2 2 5

数据

set.seed(42)
df2 <- data.frame(date=seq(as.Date("2016-11-01"), as.Date("2018-11-01"), "day"),
                  flooded=rbinom(731, 1, .5))
date.end2 <- sort(sample(df2$date, 12))
period2 <- c(4, 6, 9)

最新更新