按月和年连续观察

Consecutive observations by Month and Year

感谢你们迄今为止的帮助!只想在最后一个问题上获得一些帮助。这是我的数据...

Year Month Day Hour   DateTime
1950  1     4   12    1/4/1950 12:00
1950  1     4   13    1/4/1950 13:00 
1950  1     4   14    1/4/1950 14:00 
1950  1     4   15    1/4/1950 15:00 
1950  1     4   18    1/4/1950 18:00 
1950  1     4   21    1/4/1950 21:00 
1950  1     4   22    1/4/1950 22:00 
1950  1     5   23    1/5/1950 23:00

我将数据隔开,这样您就可以看到哪些数据与哪一列对应

我在下面使用了这段代码..

rle(cumsum(c(TRUE, diff(dt, unit = "hour") != 1)))$lengths

创建一个值列表,表示连续观察的次数。因此,例如,第一个值是 4(因为前四个观察值是连续的),然后是 1,然后是 3。这正是我想要的,但我希望按月和年获得这些值。例如,我希望我的结果如下所示...

Year Month Consecutive 
1950   1      4 
1950   1      1 
1950   1      3

其中连续列对应于上述数据中连续值的数量,但也按年份和月份。我不关心在几个月或几年结束时切断事件。目前,我不知道月份和年份在哪里,只是简单的连续总和列表!!!另外,感谢提供第一个代码的人!

我们可以做一个group by操作(假设'DateTime'转换为datetime class)

library(dplyr)
library(tidyr)
df1 %>%
   mutate(DateTime = as.POSIXct(DateTime, format = "%m/%d/%Y %H:%M")) %>%
   group_by(Year, Month) %>% 
   summarise(Consecutive = list(rle(cumsum(c(TRUE, 
         diff(DateTime, unit = "hour") != 1)))$lengths)) %>%
   unnest

数据

df1 <- structure(list(Year = c(1950L, 1950L, 1950L, 1950L, 1950L, 1950L, 
1950L, 1950L), Month = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), Day = c(4L, 
 4L, 4L, 4L, 4L, 4L, 4L, 5L), Hour = c(12L, 13L, 14L, 15L, 18L, 
 21L, 22L, 23L), DateTime = c("1/4/1950 12:00", "1/4/1950 13:00", 
 "1/4/1950 14:00", "1/4/1950 15:00", "1/4/1950 18:00", "1/4/1950 21:00", 
 "1/4/1950 22:00", "1/5/1950 23:00")), class = "data.frame",
 row.names = c(NA, -8L))