如何转换字符串
t <- c("00:00:0.00", "00:00:0.34")
成了一个数字?
尝试了几种方法 - 但没有一种方法有效..
答案 0 :(得分:10)
基本思路是将您的字符串转换为有效的POSIX*t
对象,然后将其转换为numeric
值:
## 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
请注意,在从数字转换回POSIX*t
时,存在可以更改这些对象的打印方式的浮点问题。 (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"