【问题标题】:Count the number of active episodes per month from data with start and end dates根据开始日期和结束日期的数据计算每月活跃剧集的数量
【发布时间】:2018-08-23 09:17:25
【问题描述】:

我正在尝试使用每个客户的剧集具有开始和结束日期的数据来获取每月活跃客户的数量。我正在使用的代码无法计算出如何计算每月,而不是每 n 天。

这是一些示例数据:

Start.Date <- as.Date(c("2014-01-01", "2014-01-02","2014-01-03","2014-01-03"))

End.Date<- as.Date(c("2014-01-04", "2014-01-03","2014-01-03","2014-01-04"))

确保日期是日期:

Start.Date <- as.Date(Start.Date, "%d/%m/%Y")

End.Date <- as.Date(End.Date, "%d/%m/%Y")

这是我正在使用的代码,当前计算每天的数量:

library(plyr)

count(Reduce(c, Map(seq, start.month, end.month, by = 1)))

返回:

          x freq

1 2014-01-01         1

2 2014-01-02         2

3 2014-01-03         4

4 2014-01-04         2

“by”参数可以更改为我想要的任何天数,但是由于月份的长度不同,因此会出现问题。

谁能建议我如何计算每个月?

非常感谢。

注意:我现在意识到,对于我的示例数据,我只使用了同一个月的日期,但我的真实数据的日期跨度为 3 年。

【问题讨论】:

  • 尝试通过lubridate 包。有几个处理日期/时间类的函数

标签: r date plyr duration


【解决方案1】:

这是一个似乎可行的解决方案。首先,我设置了种子,以便示例可重现。

# Set seed for reproducible example
set.seed(33550336)

接下来,我创建一个虚拟数据框。

# Test data
df <- data.frame(Start_date = as.Date(sample(seq(as.Date('2014/01/01'), as.Date('2015/01/01'), by="day"), 12))) %>% 
  mutate(End_date = as.Date(Start_date + sample(1:365, 12, replace = TRUE)))

看起来像,

#    Start_date   End_date
# 1  2014-11-13 2015-09-26
# 2  2014-05-09 2014-06-16
# 3  2014-07-11 2014-08-16
# 4  2014-01-25 2014-04-23
# 5  2014-05-16 2014-12-19
# 6  2014-11-29 2015-07-11
# 7  2014-09-21 2015-03-30
# 8  2014-09-15 2015-01-03
# 9  2014-09-17 2014-09-26
# 10 2014-12-03 2015-05-08
# 11 2014-08-03 2015-01-12
# 12 2014-01-16 2014-12-12

下面的函数采用开始日期和结束日期,并在这些日期之间创建一系列月份。

# Sequence of months
mon_seq <- function(start, end){
  # Change each day to the first to aid month counting
  day(start) <- 1
  day(end) <- 1

  # Create a sequence of months
  seq(start, end, by = "month")
}

是的,这是棘手的一点。我使用mapply 将我的函数mon_seq 应用于数据框中的所有行。这给出了每个开始日期和结束日期之间的月份。然后,我将所有这些月份组合成一个向量。我格式化这个向量,以便日期只包含月份和年份。最后,我将(使用dplyr%&gt;%)通过管道传输到table,它计算年月的每次出现,并将其转换为数据框。

data.frame(format(do.call("c", mapply(mon_seq, df$Start_date, df$End_date)), "%Y-%m") %>% table)

这给了,

#          . Freq
# 1  2014-01    2
# 2  2014-02    2
# 3  2014-03    2
# 4  2014-04    2
# 5  2014-05    3
# 6  2014-06    3
# 7  2014-07    3
# 8  2014-08    4
# 9  2014-09    6
# 10 2014-10    5
# 11 2014-11    7
# 12 2014-12    8
# 13 2015-01    6
# 14 2015-02    4
# 15 2015-03    4
# 16 2015-04    3
# 17 2015-05    3
# 18 2015-06    2
# 19 2015-07    2
# 20 2015-08    1
# 21 2015-09    1

【讨论】:

  • 谢谢,这解释得很漂亮,效果很好。
猜你喜欢
  • 2020-10-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-12
  • 2020-08-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多