2014-10-16 11 views
17

R ha is.vector, is.list, is.integer, is.double, is.numeric, is.factor, is.character, ecc Perché non c'è is.POSIXct, is.POSIXlt o is.Date?modo affidabile per rilevare se una colonna in un data.frame is.POSIXct

Ho bisogno di un modo affidabile per rilevare l'oggetto POSIXct e class(x)[1] == "POSIXct" sembra davvero ... sporco.

+3

Se si controlla solo la classe, 'inherits' probabilmente si sentirà più pulito. – joran

risposta

17

Io personalmente basta usare inherits come joran suggerito. Potresti usarlo per creare la tua funzione 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 
12

Il pacchetto lubridate ha is.POSIXt, is.POSIXct, is.POSIXlt e is.Date funzioni.

+0

Ovviamente. Sto provando a farlo nella base R e mi sono dimenticato della lubridata. – Zach

+1

Se 'x <- as.POSIXlt (Sys.time())', allora 'is.POSIXt (x)' è 'TRUE' anche se' x' non è POSIXct ... –

+0

'is.POSIXt' restituisce VERO se la classe è "POSIXlt" o "POSIXct". – eipi10

3

Si può provare is(). Questo è ciò che le funzioni lubridateis.Date e is.POSIX* si basano comunque.

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 
+1

Non che ciò sia veramente importante in questo caso, ma 'inherits' è stato progettato per S3 e va direttamente al codice C, mentre' is' deve gestire S4 e effettua diverse chiamate ad altre funzioni R. –

Problemi correlati