Home > Net >  Checking the number of observations for each ID within 8 day periods
Checking the number of observations for each ID within 8 day periods

Time:03-31

In the data set below, I would like to know how many observations each ID has in 8 day chunks. What would be the best way to approach this?

library(lubridate)
library(tidyverse)

date <- rep_len(seq(dmy("01-01-2013"), dmy("31-12-2013"), by = "days"), 300)
ID <-  rep(c("A","B","C"), 50)
deer <- data.frame(date = date,
                   utm_x = runif(length(date), min = 238785, max = 453354.5),
                   utm_y = runif(length(date), min = 4096853.0  , max = 4280487.1 ),
                   ID)

deer$julian <- yday(as.Date(deer$date))
deer$month <- month(deer$date)
deer$year <- year(deer$date)

I have been able to get the total number of observations for each ID, but I'm unsure on how to see how many observations each ID has within each 8 day period in the data set:

# Observation Distribution 
count <- data.frame(table(df$AnimalID))
colnames(count)[1] <- "ID"

CodePudding user response:

We may create a grouping variable with ceiling_date and then get the count or summarise with n()

library(dplyr)
library(lubridate)
deer %>% 
  group_by(ID) %>%
  mutate(eight_day_period = ceiling_date(date, "8 day")) %>%
  ungroup %>%
  count(ID, eight_day_period)
  • Related