将事件发生的天数分配到不同的月份

时间:2015-06-12 13:13:15

标签: r

我有一个在不同时间段发生的不同事件的数据集。

我想计算每个事件跨越每月的天数。

这是数据框。

dat = structure(list(event = structure(c(2L, 1L, 2L, 1L, 3L, 1L, 3L, 
1L, 2L, 1L, 3L, 1L, 2L, 1L, 1L, 1L, 3L, 1L, 1L, 2L), .Label = c("Event1", 
"Event2", "Event3"), class = "factor"), startDateTime = structure(c(1370995200, 
1370649600, 1370476800, 1370304000, 1370131200, 1370131200, 1370044800, 
1368316800, 1366848000, 1363824000, 1363737600, 1363046400, 1363046400, 
1362873600, 1362009600, 1360627200, 1357776000, 1357689600, 1357689600, 
1356739200), tzone = "UTC", class = c("POSIXct", "POSIXt")), 
    endDateTime = structure(c(1371686400, 1371686400, 1370908800, 
    1370476800, 1370649600, 1370131200, 1370476800, 1368489600, 
    1366934400, 1364083200, 1366502400, 1363219200, 1365897600, 
    1363219200, 1362182400, 1363132800, 1360454400, 1357776000, 
    1357862400, 1356998400), tzone = "UTC", class = c("POSIXct", 
    "POSIXt"))), .Names = c("event", "startDateTime", "endDateTime"
), row.names = c(NA, -20L), class = "data.frame")

我从搜索中发现,我可以使用动物园包计算每个月的事件天数,如下:

library(zoo)

table(as.yearmon(seq(dat$startDateTime[20], dat$endDateTime[20], "day")))

Dec 2012 Jan 2013 
3        1

我想扩展和概括这一点,以便我可以将它应用于整个 数据帧并计算每个事件每个事件跨越不同事件的天数。这是使用lubridate可以实现的吗?

对此的任何指示都将非常感激。

2 个答案:

答案 0 :(得分:1)

使用其主体几乎是您的代码的函数在行索引上尝试nr <- nrow(dat) result <- lapply(1:nr, function(i) table(as.yearmon(seq(dat$startDateTime[i], dat$endDateTime[i], "day"))) ) 。它将生成一个每行包含一个组件的列表:

nr <- nrow(dat)
L <- lapply(1:nr, function(i) {
  tab <- table(as.yearmon(seq(dat$startDateTime[i], dat$endDateTime[i], "day")))
  data.frame(Row = i, tab)
})
do.call("rbind", L)

或生成data.frame输出:

{{1}}

答案 1 :(得分:1)

你可以尝试

 library(data.table)
 library(lubridate)
 library(zoo)
 setDT(dat)[, list(as.yearmon(seq(min(startDateTime), max(endDateTime), 
             by='day'))) , event][, .N, list(event, V1)]
相关问题