6

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..

Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
Kay
  • 2,702
  • 6
  • 32
  • 48

1 Answers1

11

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"
Community
  • 1
  • 1
Josh O'Brien
  • 159,210
  • 26
  • 366
  • 455
  • +1 What's the motivation for the extra parentheses, if you don't mind me asking? – Matthew Plourde Apr 09 '13 at 18:02
  • 1
    @MatthewPlourde -- They just force printing of an object's value, even when it's been assigned to an symbol. (Compare `x <- rnorm(5)` and `(x <- rnorm(5))`. I put them there b/c I generally want my answers to be self-contained and runnable by copy and pasting them from SO into an R session, although I can see that they're a little distracting ;) – Josh O'Brien Apr 09 '13 at 18:08
  • no criticism at all. asked because I expected to learn something...and I did! thanks. – Matthew Plourde Apr 09 '13 at 18:10
  • @MatthewPlourde No problem. I didn't take it as criticism, and recall wondering the same thing myself once, back in the mists of time... – Josh O'Brien Apr 09 '13 at 18:23
  • @JoshO'Brien: The `"%S%OS"` part gives me trouble when the number of "full" seconds is larger than zero -- but `"%OS"` works. I understand that `"%OS"` matches both integer and fractional parts of the second. – krlmlr Mar 23 '15 at 15:07
  • @krlmlr -- Woah. Thanks for the great catch! Fixed now. – Josh O'Brien Mar 23 '15 at 15:16