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 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.
First, we need to install and load the lubridate package:
install.packages("lubridate") # Install & load lubridate package library("lubridate")
Next, 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.
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
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.
- Convert Integer to Date in R
- Get End of Month for Certain Date
- Get Difference Between Dates in Years
- Check if Number is Integer in R
- Check if Column Exists in Data Frame
- Create Data Frame where a Column is a List
- Introduction to R
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.
Statistics Globe Newsletter