Reliable way to detect if a column in a data.frame is.POSIXct
Asked Answered
S

3

36

R has is.vector, is.list, is.integer, is.double, is.numeric, is.factor, is.character, etc. Why is there no is.POSIXct, is.POSIXlt or is.Date?

I need a reliable way to detect POSIXct object, and class(x)[1] == "POSIXct" seems really... dirty.

Sat answered 16/10, 2014 at 20:5 Comment(1)
If you do just check the class, inherits would probably feel cleaner.Phantom
A
38

I would personally just use inherits as joran suggested. You could use it to create your own is.POSIXct function.

# 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 
Adina answered 16/10, 2014 at 20:57 Comment(0)
B
22

The lubridate package has is.POSIXt, is.POSIXct, is.POSIXlt, and is.Date functions.

Briones answered 16/10, 2014 at 20:8 Comment(5)
Of course. I'm trying to do this in base R and forgot about lubridate.Sat
If x <- as.POSIXlt(Sys.time()), then is.POSIXt(x) is TRUE even though x is not POSIXct...Adina
is.POSIXt returns TRUE if the class is either POSIXlt or POSIXct.Briones
Yes, that was my point. It does not help you differentiate between POSIXct and POSIXlt.Adina
Clarification added. Thanks.Briones
K
9

You can try is(). This is what the lubridate functions is.Date and is.POSIX* rely on anyway.

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
Kersten answered 16/10, 2014 at 20:14 Comment(1)
Not that it really matters in this case, but inherits was designed for S3 and goes straight to C code, while is needs to handle S4 and makes several calls to other R functions.Adina

© 2022 - 2024 — McMap. All rights reserved.