检测data.frame中的列是否为.POSIXct的可靠方法 [英] Reliable way to detect if a column in a data.frame is.POSIXct

查看:82
本文介绍了检测data.frame中的列是否为.POSIXct的可靠方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

R具有 is.vector is.list is.integer is.double is.numeric is.factor is.character 等.为什么没有 is.POSIXct is.POSIXlt is.Date ?

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?

我需要一种可靠的方法来检测 POSIXct 对象,并且 class(x)[1] =="POSIXct" 似乎真的很脏.

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

推荐答案

我个人只是将 inherits 用作

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 

这篇关于检测data.frame中的列是否为.POSIXct的可靠方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆