6

如何转换字符串

t <- c("00:00:0.00", "00:00:0.34")

成一个数字?尝试了几种方法 - 但没有一个奏效..

4

1 回答 1

11

基本思想是将字符串转换为有效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

请注意,当从 numeric 转换回 时POSIX*t,会出现浮点问题,这些问题会改变这些对象的打印方式。(有关该问题的更多讨论,请参见此处。

## 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"
于 2013-04-09T16:38:04.230 回答