How to Check if Column is Date in R (With Examples)


You can use the is.Date function from the lubridate package in R to quickly check if a data frame column is a date.

There are two common ways to use this function in practice:

Method 1: Check if One Specific Column is Date

library(lubridate)

#check if 'sales' column is date
is.Date(df$sales)

Method 2: Check if Each Column in Data Frame is Date

library(lubridate)

#check if each column in data frame is date
sapply(df, is.Date)

The following examples show how to use each method in practice with the following data frame in R:

#create data frame
df <- data.frame(date = as.Date('2023-01-01') + 0:9,
                 sales = c(12, 14, 7, 7, 6, 8, 10, 5, 11, 8),
                 refunds = c(2, 0, 0, 3, 2, 1, 1, 0, 0, 4))

#view data frame
df

         date sales refunds
1  2023-01-01    12       2
2  2023-01-02    14       0
3  2023-01-03     7       0
4  2023-01-04     7       3
5  2023-01-05     6       2
6  2023-01-06     8       1
7  2023-01-07    10       1
8  2023-01-08     5       0
9  2023-01-09    11       0
10 2023-01-10     8       4

Example 1: Check if One Specific Column is Date

The following code shows how to check if the sales column is a date:

library(lubridate)

#check if 'sales' column is date
is.Date(df$sales)

[1] FALSE

The function returns FALSE, which tells us that the sales column is not a date column.

Example 2: Check if Each Column in Data Frame is Date

The following code shows how to check if each column in the data frame is a date:

library(lubridate)

#check if each column in data frame is date
sapply(df, is.Date)

   date   sales refunds 
   TRUE   FALSE   FALSE 

The output returns either TRUE or FALSE for each column in the data frame to indicate if it is a date.

From the output we can see:

  • The date column is a date.
  • The sales column is not a date.
  • The refunds column is not a date.

Note: If you’d like to see the class of each column in the data frame, you can use the sapply function combined with the class function as follows:

#view class of each column in data frame
sapply(df, class)

     date     sales   refunds 
   "Date" "numeric" "numeric" 

The output displays the class of each column in the data frame.

Related: A Guide to apply(), lapply(), sapply(), and tapply() in R

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Plot a Time Series in R
How to Extract Year from Date in R
How to Check if Date is Between Two Dates in R

Leave a Reply

Your email address will not be published. Required fields are marked *