R Create a simple time table

Check this simple time table  function that generates a time table for any given date!

You can control the time interval, as well!


make.ts <- function (date, deltaInSec) {

require (data.table)

#input:
 # date : variable in date object
 # deltaInSec : time interval in sec

date1 <- as.character(date)
date2 <- as.character(as.Date(date1) + 1)

time_beg <- as.numeric(as.POSIXct(date1, tz = "gmt", origin = "1970-01-01"))
time_end <- as.numeric(as.POSIXct(date2, tz = "gmt", origin = "1970-01-01")) - 1

dt <- data.table (timeInSecondsSinceEpoch = time_beg : time_end)

dt[, timeInSecondsSinceEpoch := floor(timeInSecondsSinceEpoch / deltaInSec) * deltaInSec]

dt <- unique(dt)

dt[, gmt := as.POSIXct(timeInSecondsSinceEpoch, tz = "GMT", origin = "1970-01-01")]

return (dt)

}

 

Let’s run this function!

 


today <- Sys.Date ()</pre>

make.ts(date = today, deltaInSec = 1)

make.ts(date = today, deltaInSec = 60)

make.ts(date = today, deltaInSec = 3600)

The outputs are like this:

make.ts output

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s