as_datetime() Error: All formats failed to parse
as_datetime() Error: All formats failed to parse
为什么 as_datetime() 在以下示例中导致 NA?
x <- dmy("1-1-2000")
y <- "14:30"
as_datetime(paste(x, y))
错误:
[NA]
Warning message:
All formats failed to parse. No formats found.
谢谢
我们可以使用format
参数
library(lubridate)
as_datetime(paste(x, y), format = "%Y-%m-%d %H:%M")
#[1] "2000-01-01 14:30:00 UTC"
或者另一种选择是anytime
library(anytime)
anytime(paste(x, y))
#[1] "2000-01-01 14:30:00 EST"
原因可能是它希望时间采用 %H:%M:%S
格式,而 'y' 不是。如果我们使用完整格式而不是%H:%M
(也可以判断为%M:%S
)
y1 <- "14:30:00"
as_datetime(paste(x, y1))
#[1] "2000-01-01 14:30:00 UTC"
注意:这回答了 OP 收到警告消息的原因。
由于您已经在使用 lubridate,您只需在之前设置 hm
将日期对象 dmy
添加到时间对象(小时:分钟)。
x <- dmy("1-1-2000")
y <- "14:30"
z <- x + hm(y)
参见:R tick data : merging date and time into a single object
为什么 as_datetime() 在以下示例中导致 NA?
x <- dmy("1-1-2000")
y <- "14:30"
as_datetime(paste(x, y))
错误:
[NA]
Warning message:
All formats failed to parse. No formats found.
谢谢
我们可以使用format
参数
library(lubridate)
as_datetime(paste(x, y), format = "%Y-%m-%d %H:%M")
#[1] "2000-01-01 14:30:00 UTC"
或者另一种选择是anytime
library(anytime)
anytime(paste(x, y))
#[1] "2000-01-01 14:30:00 EST"
原因可能是它希望时间采用 %H:%M:%S
格式,而 'y' 不是。如果我们使用完整格式而不是%H:%M
(也可以判断为%M:%S
)
y1 <- "14:30:00"
as_datetime(paste(x, y1))
#[1] "2000-01-01 14:30:00 UTC"
注意:这回答了 OP 收到警告消息的原因。
由于您已经在使用 lubridate,您只需在之前设置 hm
将日期对象 dmy
添加到时间对象(小时:分钟)。
x <- dmy("1-1-2000")
y <- "14:30"
z <- x + hm(y)
参见:R tick data : merging date and time into a single object