Check if Column is Date in R (Example)

 

In this R programming tutorial you’ll learn how to test whether a data frame variable has the Date class.

The tutorial will contain the following contents:

You’re here for the answer, so let’s get straight to the example.

 

Construction of Example Data

To begin with, we’ll have to create some exemplifying data:

data <- data.frame(x1 = 1:3,    # Create example data frame
                   x2 = as.Date(c("2022-10-10", "2024-03-19", "2022-12-07")),
                   x3 = c("2023-11-02", "2025-01-17", "2022-10-04"))
data                            # Print example data frame

 

table 1 data frame check if column is date

 

Table 1 illustrates the output of the RStudio console returned after executing the previous R programming syntax and shows that the example data consists of three data points and the three variables “x1”, “x2”, and “x3”.

 

Example: Test which Columns of Data Frame have Date Class Using sapply() & is.Date() Functions

The following code illustrates how to check for each column of a data frame whether it has the Date class.

For this task, we can apply the sapply and is.Date functions as shown below:

sapply(data, is.Date)           # Test for Date class
#    x1    x2    x3 
# FALSE  TRUE FALSE

The previous output of the RStudio console shows that only the variable x2 has the Date class.

This might be surprising, since the variable x3 contains date values as well. However, this variable has not been properly converted to a date using the as.Date function.

 

Video, Further Resources & Summary

Do you want to learn more about the checking if a data frame variable has the Date class? Then I can recommend having a look at the following video on my YouTube channel. In the video, I show the R programming codes of this tutorial.

 

The YouTube video will be added soon.

 

In addition to the video, you could read the related articles on this website. I have published several other articles on related topics such as lists, numeric values, and extracting data.

 

To summarize: In this tutorial, I have demonstrated how to check if a data frame column has the Date class in R. If you have further questions, please tell me about it in the comments.

 

Subscribe to the Statistics Globe Newsletter

Get regular updates on the latest tutorials, offers & news at Statistics Globe.
I hate spam & you may opt out anytime: Privacy Policy.


Leave a Reply

Your email address will not be published.

Fill out this field
Fill out this field
Please enter a valid email address.

Menu
Top