我怎样才能在R中巧妙地找到以前的时间段开始和结束?

问题描述 投票:2回答:3

我想在R中找到前一个时期的开始和结束。期间以分钟为单位。

会喜欢下面的输出。

library(lubridate)
timeNow <- now()
timeNow
# [1] "2019-04-17 11:17:09 CEST"

periodLength <- 60    #minutes
previousPeriodStart(timeNow, periodLength)
# [1] "2019-04-17 10:00:00 CEST"
previousPeriodEnd(timeNow, periodLength)
# [1] "2019-04-17 10:59:59 CEST"

periodLength <- 5    #minutes
previousPeriodStart(timeNow, periodLength)
# [1] "2019-04-17 11:10:00 CEST"
previousPeriodEnd(timeNow, periodLength)
# [1] "2019-04-17 11:14:59 CEST"

我知道如果我有数据的ts,如何在xts中构建这些函数。由于我没有此示例的数据集,因此无法使用xts to.period函数。我只是想找到开始和结束。

构建previousPeriodStart和previousPeriodEnd最聪明的方法是什么?或者我应该开始使用epoch / unix时间进行一些算术运算?

非常感谢提前。

---编辑----由于接收的答案功能可以同时回答开始和结束的功能,因此当然要聪明得多。

r xts lubridate
3个回答
3
投票

使用lubridate可以轻松完成:

previousPeriod <- function(timeNow,periodLength)
{
  start <- floor_date(timeNow - minutes(60),"hour")
  end <- ceiling_date(timeNow - minutes(60),"hour") - seconds(1)
  return(c(start=start,end=end))
}

previousPeriod(timeNow,periodLength)

                    start                       end 
"2019-04-17 10:00:00 UTC" "2019-04-17 10:59:59 UTC" 

3
投票

像这样的东西?

library(lubridate)
timeNow <- now()

period = 60

floor_date(timeNow, unit="hour")-minutes(period)+minutes( trunc(minute(timeNow)/period)*period)
floor_date(timeNow, unit="hour")-minutes(period)+minutes( trunc(minute(timeNow)/period)*period)+minutes(period)-seconds(1)

period = 5

floor_date(timeNow, unit="hour")-minutes(period)+minutes( trunc(minute(timeNow)/period)*period)
floor_date(timeNow, unit="hour")-minutes(period)+minutes( trunc(minute(timeNow)/period)*period)+minutes(period)-seconds(1)

1
投票

在使用floor_date的其他答案的基础上,我已经改进了最快的答案,还包括其他分钟间隔的工作代码而不是整个小时。

previousPeriods <- function(timeNow, periodLength)
{
  periodPhrase <- paste0(periodLength, " mins")  # To create periods such as "5 mins"
  start <- floor_date(timeNow - minutes(periodLength), periodPhrase)
  end <- ceiling_date(timeNow - minutes(periodLength), periodPhrase) - seconds(1)
  return(c(start=start,end=end))
}

再次感谢快速解答的所有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.