假设我们的数据框定义如下:
mydata <- data.frame(id = c('A', 'B', 'C', 'D'),
start_date = as.Date(c('2012-08-05',
'2013-05-04',
'2012-02-01',
'2015-03-02')),
end_date = as.Date(c('2014-01-12',
'2015-06-05',
'2016-05-06',
'2017-09-12')))
Run Code Online (Sandbox Code Playgroud)
凡start_date有关两天的会谈雇员加入和end_date有关两天的会谈,他离开,并id是唯一的雇员ID.
对于从2012年8月5日(最早start_date)到2017年9月12日(最新end_date)的每个月,我希望员工数月亮.最终输出的格式应与下面的格式类似:(如果是宽格式或长格式则无关紧要)

在上表中,列表示月份(1到12),年份行和表格中的单元格表示该月份的员工数量.
任何帮助将受到高度赞赏.
这是mapply基础R 的解决方案.
# Function to get date of first day of a month (by @digEmAll)
toFirstDayOfMonth <- function(dates) dates - as.POSIXlt(dates)$mday + 1
# Generate all dates
dates <- Reduce(c, with(mydata, mapply(seq, toFirstDayOfMonth(start_date), end_date,
by = "month")))
# Count occurrences of year/month combinations
table(format(dates, "%Y"), format(dates, "%m"))
Run Code Online (Sandbox Code Playgroud)
结果:
01 02 03 04 05 06 07 08 09 10 11 12
2012 0 1 1 1 1 1 1 2 2 2 2 2
2013 2 2 2 2 3 3 3 3 3 3 3 3
2014 3 2 2 2 2 2 2 2 2 2 2 2
2015 2 2 3 3 3 3 2 2 2 2 2 2
2016 2 2 2 2 2 1 1 1 1 1 1 1
2017 1 1 1 1 1 1 1 1 1 0 0 0
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
157 次 |
| 最近记录: |