R有is.vector
、is.list
、is.integer
、is.double
、is.numeric
、is.factor
、is.character
等函数,为什么没有is.POSIXct
、is.POSIXlt
或is.Date
函数呢?
我需要一种可靠的方式来检测POSIXct
对象,而class(x)[1] == "POSIXct"
似乎很...不太好。
我个人会像joran建议的那样,只使用inherits
。你可以使用它来创建自己的is.POSIXct
函数。
# functions
is.POSIXct <- function(x) inherits(x, "POSIXct")
is.POSIXlt <- function(x) inherits(x, "POSIXlt")
is.POSIXt <- function(x) inherits(x, "POSIXt")
is.Date <- function(x) inherits(x, "Date")
# data
d <- data.frame(pct = Sys.time())
d$plt <- as.POSIXlt(d$pct)
d$date <- Sys.Date()
# checks
sapply(d, is.POSIXct)
# pct plt date
# TRUE FALSE FALSE
sapply(d, is.POSIXlt)
# pct plt date
# FALSE TRUE FALSE
sapply(d, is.POSIXt)
# pct plt date
# TRUE TRUE FALSE
sapply(d, is.Date)
# pct plt date
# FALSE FALSE TRUE
lubridate
包提供了 is.POSIXt
,is.POSIXct
,is.POSIXlt
和 is.Date
函数。
x <- as.POSIXlt(Sys.time())
,那么即使 x
不是 POSIXct,is.POSIXt(x)
也会返回 TRUE
... - Joshua UlrichPOSIXlt
或 POSIXct
,则 is.POSIXt
返回 TRUE。 - eipi10is()
函数。这也是lubridate
函数中的is.Date
和is.POSIX*
所依赖的函数。x <- Sys.time()
class(x)
# [1] "POSIXct" "POSIXt"
is(x, "Date")
#v[1] FALSE
is(x, "POSIXct")
# [1] TRUE
y <- Sys.Date()
class(y)
# [1] "Date"
is(y, "POSIXct")
# [1] FALSE
is(y, "Date")
# [1] TRUE
inherits
是为了 S3 而设计的,可以直接进入 C 代码,而 is
则需要处理 S4,并调用其他 R 函数。 - Joshua Ulrich
inherits
可能会更加简洁。 - joran