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

问题描述 投票:1回答:1

我有一个雨量计记录的数据。它记录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
r date events
1个回答
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))

0
投票

这里是另一个解决方案,使用:

library(lubridate)
library(dplyr)

floor.dates <- floor_date(as.POSIXct(df$V2),unit = "hour")
allDates <- seq.POSIXt(
  min(floor.dates),
  max(floor.dates),by = "1 hour")

allValues <- merge(
  x = data.frame(Date = allDates),
  y = data.frame(Date = floor.dates,rain = df[,3]),
  all.x = TRUE) %>% 
  mutate_if(is.numeric, ~replace(.x, is.na(.x), 0))

输出:

> allValues
                 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.2
7 2018-10-08 16:00:00  0.2
8 2018-10-08 16:00:00  0.2
© www.soinside.com 2019 - 2024. All rights reserved.