Working with timestamps in R

I have several dimension lists. Each list has a timestramp formed as a string ("2009-12-24 21: 00: 07.0"), and I know that each dimension in the list is divided by 5 seconds. I want to combine all the data into a huge data.frame in R. After that I want to be able to easily access the time difference of the two dimensions, so I probably should convert the data to something other than characters.

What format should be used to store time? Is there some kind of time format in some kind of package that I should use?

+45
timestamp time r
Dec 25 '09 at 23:58
source share
1 answer

You want a (standard) POSIXt type from the R base, which can be used in "compact form", like POSIXct (which is essentially double representing fractional seconds from the era) or as a long form in POSIXlt (which contains subelements). The most interesting thing is that arithmetic, etc. Defined on this - see help(DateTimeClasses)

Quick example:

 R> now <- Sys.time() R> now [1] "2009-12-25 18:39:11 CST" R> as.numeric(now) [1] 1.262e+09 R> now + 10 # adds 10 seconds [1] "2009-12-25 18:39:21 CST" R> as.POSIXlt(now) [1] "2009-12-25 18:39:11 CST" R> str(as.POSIXlt(now)) POSIXlt[1:9], format: "2009-12-25 18:39:11" R> unclass(as.POSIXlt(now)) $sec [1] 11.79 $min [1] 39 $hour [1] 18 $mday [1] 25 $mon [1] 11 $year [1] 109 $wday [1] 5 $yday [1] 358 $isdst [1] 0 attr(,"tzone") [1] "America/Chicago" "CST" "CDT" R> 

Regarding reading them, see help(strptime)

As for the difference, it’s also easy:

 R> Jan1 <- strptime("2009-01-01 00:00:00", "%Y-%m-%d %H:%M:%S") R> difftime(now, Jan1, unit="week") Time difference of 51.25 weeks R> 

Finally, zoo package is an extremely versatile and well-documented container for the matrix with corresponding date and time indices.

+57
Dec 26 '09 at 0:45
source share



All Articles