How to convert the string
t <- c("00:00:0.00", "00:00:0.34")
into a number? tried several approaches - but none of them worked..
To convert characters to time objects in R, use the strptime() function. To convert time objects to characters in R, use the strftime() function.
POSIXct stores date and time in seconds with the number of seconds beginning at 1 January 1970. Negative numbers are used to store dates prior to 1970. Thus, the POSIXct format stores each date and time a single value in units of seconds. Storing the data this way, optimizes use in data.
The strptime function converts characters to time objects and uses the following basic syntax: strptime(character_object, format="%Y-%m-%d") The strftime function converts time objects to characters and uses the following basic syntax: strftime(time_object)
The basic idea is to convert your character string to a valid POSIX*t
object, and then convert that to a numeric
value:
## Set a couple of printing options
options(digits = 12)
options(digits.secs = 3)
## Convert from character to POSIXlt to numeric
(a <- strptime(t, format="%H:%M:%OS", tz="GMT"))
# [1] "2013-04-09 00:00:00.00 GMT" "2013-04-09 00:00:00.34 GMT"
(b <- as.numeric(a))
# [1] 1365465600.00 1365465600.34
Note that, when converting back from numeric to POSIX*t
, there are floating point issues that can change how those objects are printed. (See here for more discussion of that issue.)
## It _looks_ like you've lost 1/100 second on the second time object
(c <- as.POSIXct(as.numeric(b), origin = "1970-01-01", tz="GMT"))
# [1] "2013-04-09 00:00:00.00 GMT" "2013-04-09 00:00:00.33 GMT"
## Here's a workaround for nicer printing.
as.POSIXct(as.numeric(b+1e-6), origin = "1970-01-01", tz="GMT")
# [1] "2013-04-09 00:00:00.00 GMT" "2013-04-09 00:00:00.34 GMT"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With