R- Calculate a count of items over time using start and end dates

后端 未结 5 1274
隐瞒了意图╮
隐瞒了意图╮ 2021-01-05 17:22

I want to calculate a count of items over time using their Start and End dates.

Some sample data

START <- as.Date(c(\"2014-01-01\", \"2014-01-02\         


        
5条回答
  •  无人及你
    2021-01-05 18:22

    Using dplyr and foreach:

    library(dplyr)
    library(foreach)
    
    df <- data.frame(START = as.Date(c("2014-01-01",
                                       "2014-01-02",
                                       "2014-01-03",
                                       "2014-01-03")),
                     END = as.Date(c("2014-01-04",
                                     "2014-01-03",
                                     "2014-01-03",
                                     "2014-01-04")))
    df
    
    r <- foreach(DATETIME = seq(min(df$START), max(df$END), by = 1),
                 .combine = rbind) %do% {
      df %>%
        filter(DATETIME >= START & DATETIME <= END) %>%
        summarise(DATETIME, COUNT = n())
    }
    r
    

提交回复
热议问题