Is there a way to check if a column is a Date in R?

You could try to coerce all the columns to as.Date and see which ones succeed. You would need to specify the format you expect dates to be in though. E.g.:

data <- data.frame(
  Date=c("10/11/2012","10/12/2012"),
  AE=c(1211,100),
  Percent=c(0.03,0.43)
)

sapply(data, function(x) !all(is.na(as.Date(as.character(x),format="%d/%m/%Y"))))
#Date      AE Percent 
#TRUE   FALSE   FALSE 

Use inherits to detect if argument has datatype Date:

is.date <- function(x) inherits(x, 'Date')

sapply(list(as.Date('2000-01-01'), 123, 'ABC'), is.date)
#[1]  TRUE FALSE FALSE

If you want to check if character argument can be converted to Date then use this:

is.convertible.to.date <- function(x) !is.na(as.Date(as.character(x), tz = 'UTC', format = '%Y-%m-%d'))

sapply(list('2000-01-01', 123, 'ABC'), is.convertible.to.date)
# [1]  TRUE FALSE FALSE

Tags:

R