Skip to content

Instantly share code, notes, and snippets.

@shiraco
Last active December 23, 2015 05:39
Show Gist options
  • Save shiraco/6588958 to your computer and use it in GitHub Desktop.
Save shiraco/6588958 to your computer and use it in GitHub Desktop.
toDateTime <- function(strTime){
strptime((strTime),format="%Y/%m/%d %H:%M")
}
> toDateTime("2012/08/12 00:00")
----
countRunning <- function(recordDateTime, startDateTime, endDateTime){
# isRunning <- ifelse(startDateTime <= recordDateTime & recordDateTime < endDateTime, 1, 0)
isRunning <- (startDateTime <= recordDateTime & recordDateTime < endDateTime) * 1
sum(isRunning)
}
> countRunning(toDateTime("2012/08/12 00:00"), data$startDateTime, data$EndDateTime)
----
# change for roop
countRunningForDateTimes <- function(recordDateTimes, startDateTime, endDateTime) {
vec <- NULL
for (recordDateTime in recordDateTimes) {
vec <- append(vec, countRunning(recordDateTime, startDateTime, endDateTime))
}
vec
}
> recordDateTimes <- seq(min(data$startDateTime), max(data$endDateTime) + 1 , by = "secs")
> runningNums <- countRunningForDateTimes(recordDateTimes, data$startDateTime, data$endDateTime)
----
POSIXlt.floor <- function(POSIXltDateTime, by = "day") {
mon <- -1
day <- -1
hour <- -1
min <- -1
sec <- -1
if(by == "min") {
sec <- 0
} else if(by == "hour") {
min <- 0
sec <- 0
} else if(by == "day") {
hour <- 0
sec <- 0
min <- 0
} else if(by == "month") {
day <- 1
hour <- 0
sec <- 0
min <- 0
} else if(by == "year") {
mon <- 0
day <- 1
hour <- 0
sec <- 0
min <- 0
}
if(mon != -1) POSIXltDateTime$mon <- mon
if(day != -1) POSIXltDateTime$mday <- day
if(hour != -1) POSIXltDateTime$hour <- hour
if(min != -1) POSIXltDateTime$min <- min
if(sec != -1) POSIXltDateTime$sec <- sec
POSIXltDateTime
}
----
POSIXlt.ceiling <- function(POSIXltDateTime, by = "day") {
dateTime <- POSIXlt.floor(POSIXltDateTime, by)
if(by == "year" ) dateTime$year <- dateTime$year + 1
if(by == "month") dateTime$mon <- dateTime$mon + 1
if(by == "day" ) dateTime$mday <- dateTime$mday + 1
if(by == "hour" ) dateTime$hour <- dateTime$hour + 1
if(by == "min" ) dateTime$min <- dateTime$min + 1
if(by == "sec" ) dateTime$sec <- dateTime$sec + 1
as.POSIXlt(as.POSIXct(dateTime))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment