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

后端 未结 5 1275
隐瞒了意图╮
隐瞒了意图╮ 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:05

    This would do it. You can change the column names as necessary.

    as.data.frame(table(Reduce(c, Map(seq, df$START, df$END, by = 1))))
    #         Var1 Freq
    # 1 2014-01-01    1
    # 2 2014-01-02    2
    # 3 2014-01-03    4
    # 4 2014-01-04    2
    

    As noted in the comments, Var1 in the above solution is now a factor, and not a date. To keep the date class in the first column, you could do some more work to the above solution, or use plyr::count instead of as.data.frame(table(...))

    library(plyr)
    count(Reduce(c, Map(seq, df$START, df$END, by = 1)))
    #            x freq
    # 1 2014-01-01    1
    # 2 2014-01-02    2
    # 3 2014-01-03    4
    # 4 2014-01-04    2
    

提交回复
热议问题