如何在R中按日期对事件求和

时间:2019-10-28 16:33:34

标签: r date events

我有一个雨量计记录的数据。它记录0.2 l / m2的事件及其发生的日期。经过一些处理后,我的数据如下所示:

    head(df)
                       V2 V3  V4
    1 2018-10-08 11:54:43  1 0.2
    2 2018-10-08 12:49:21  2 0.2
    3 2018-10-08 15:55:33  3 0.2
    4 2018-10-08 16:43:37  4 0.2
    5 2018-10-08 16:47:41  5 0.2
    6 2018-10-08 16:56:44  6 0.2

请注意,第V2列是事件发生的日期,第V3列是事件的累计计数,我按事件将V4列的值添加为l / m2。

我想按规则的日期顺序对V4列的值求和,例如每小时(或每天,或任何其他时间段),用没有事件的那些时间段“零”填充

要获得类似的东西

                     date  rain
    1 2018-10-08 11:00:00   0.2
    2 2018-10-08 12:00:00   0.2
    3 2018-10-08 13:00:00   0.0
    4 2018-10-08 14:00:00   0.0
    5 2018-10-08 15:00:00   0.2
    6 2018-10-08 16:00:00   0.6

我确实解决了这个问题,但是以一种非常复杂的方式(请参见下面的代码)。有直接的方法吗?

    df$date<-round.POSIXt(df$V2, units = "hour")

    library(xts)

    df.xts <- xts(df$V4,as.POSIXct(df$date))

    hourly<-period.apply(df.xts,endpoints(df$date,"hours"),sum)

    hourly<-as.data.frame(hourly)
    hourly$date<-as.POSIXct(rownames(hourly))

    ref<-  data.frame(date=seq.POSIXt(from=min(df$date),to=max(df$date),by="hour"))

    all<-merge(hourly,ref,by="date",all.y = TRUE)

    all$V1[is.na(all$V1)]<-0

1 个答案:

答案 0 :(得分:1)

您可以使用tidyverse

library(tidyverse) 

x <- df %>%
         group_by(date = floor_date(as.POSIXct(V2), "1 hour")) %>%
         summarize(rain = sum(V4)) 

然后填写缺少的时间:

x <- as_tibble(seq(min(x$date), max(x$date), by = "hour")) %>% 
        left_join(., x, by = c("value" = "date")) %>%
        replace_na(list(rain = 0))

#  value                rain
#  <dttm>              <dbl>
#1 2018-10-08 11:00:00   0.2
#2 2018-10-08 12:00:00   0.2
#3 2018-10-08 13:00:00   0  
#4 2018-10-08 14:00:00   0 
#5 2018-10-08 15:00:00   0.2
#6 2018-10-08 16:00:00   0.6

数据:

df <- structure(list(V2 = structure(1:6, .Label = c("     2018-10-08 11:54:43", 
"     2018-10-08 12:49:21", "     2018-10-08 15:55:33", "     2018-10-08 16:43:37", 
"     2018-10-08 16:47:41", "     2018-10-08 16:56:44"), class = "factor"), 
    V3 = 1:6, V4 = c(0.2, 0.2, 0.2, 0.2, 0.2, 0.2)), class = "data.frame", row.names = c(NA, 
-6L))