计算指定时间段内值为1的总时间

时间:2015-10-06 16:14:18

标签: r dplyr

我有一个包含两列的数据集。我需要计算在00:00到6:00之间的值大于1的总时间(以秒为单位)。我怎样才能在R中以最有效的方式做到这一点?可以使用dplyr包完成吗?我需要以通用的方式执行此操作,以便它也可以应用于其他持续时间(6到9,9到12)。以下是一些示例数据:

SUBROUTINE POISSON_SOLVER_MKL(N,M,Phi,Div,Ja,Lx,Ly,dx,dy)
IMPLICIT NONE
!
INTEGER,INTENT(IN)::N,M                ! Number of mesh intervals
REAL(DP),INTENT(IN) ::Div( 0:N, 0:M )   !This is right-hand side of PE
REAL(DP),INTENT(OUT)::Phi( 0:N, 0:M )   !This is left-hand side of PE
...
Nx = N
Ny = M

ALLOCATE( dpar(13*Nx/2+7), bd_ax(0:Ny), bd_bx(0:Ny), bd_ay(0:Nx), bd_by(0:Nx) )
...
! other parts are the same

因此,此处预期持续时间介于00到06之间的输出为15910秒。

1 个答案:

答案 0 :(得分:3)

首先我会解析日期/时间:

dat$Timestamp <- strptime(dat$Timestamp, format="%Y-%m-%d %H:%M:%S")

然后我会使用difftime

抓住每次观察之间的秒数
secs <- as.numeric(difftime(tail(dat$Timestamp, -1), head(dat$Timestamp, -1),
                            units="secs"))

最后,我将总结每个区间中具有大于1的值的秒数:

sum(secs[head(dat$Value, -1) > 1])
# [1] 15910

假设您感兴趣的时间边界出现在时间戳字段中,您可以使用以下内容限制感兴趣的时间范围(从begin.time开始到end.time结束) / p>

dat.subset <- dat[dat$Timestamp >= begin.time & dat$Timestamp <= end.time,]

数据:

dat <- data.frame(Timestamp = c("2015-10-01 00:00:00", "2015-10-01 00:00:55", "2015-10-01 00:25:10", "2015-10-01 01:05:40", "2015-10-01 02:05:40", "2015-10-01 04:05:40", "2015-10-01 05:00:00", "2015-10-01 06:00:00"), Value = c(300, 200, 0, 876, 989, 0, 600, 300))