如何转换字符串
t <- c("00:00:0.00", "00:00:0.34")
变成一个数字?
尝试了几种方法-但没有一种有效。
最佳答案
基本思想是将字符串转换为有效的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"
关于r - 以小数秒为单位的R中的日期时间转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15906584/