Taming Excel Dates in R: From Numbers to Meaningful Dates!
code
rtip
timeseries
Author
Steven P. Sanderson II, MPH
Published
February 5, 2024
Introduction
Have you ever battled with Excel’s quirky date formats in your R projects? If so, you’re not alone! Those cryptic numbers can be a real headache, but fear not, fellow R warriors! Today, we’ll conquer this challenge and transform those numbers into beautiful, usable dates.
Our Mission: We’ll convert two date columns in a tibble named “df”:
date: Stored as numbers, representing days since some mysterious date.
datetime: Also in numberland, but with an additional decimal for time.
Our Weapons:
as.Date(): This built-in R function is our date-conversion hero, but we need to give it a secret weapon: origin = "1899-12-30". This tells as.Date() where the Excel date system starts counting days from.
openxlsx library: This package helps us deal with Excel files. We’ll use its convertToDateTime() function to handle the datetime column, which includes both date and time information.
# Convert "date" column using as.Date() and the magic origindf$date <-as.Date(df$date, origin ="1899-12-30")# Convert "datetime" column using openxlsx and convertToDateTime()df$datetime <-convertToDateTime(df$datetime)
Breaking it Down
The first line checks if openxlsx is installed and loads it if needed.
We create our sample data frame df with the date and datetime columns.
The magic happens! We use as.Date() on df$date, specifying the origin as “1899-12-30”. This tells R to interpret the numbers as days since that date.
For df$datetime, we use convertToDateTime() from the openxlsx package. This function handles both date and time information stored as decimals.
Voila! Our df now has proper date and datetime columns, ready for further analysis and visualization. Let’s see the results:
head(df, 1)
date datetime sales
1 2022-01-02 2022-01-02 04:04:48 14
You’re Turn!
Now it’s your turn! Grab your own Excel data with mysterious date formats and try this code. Play with different origin values if needed (depending on your Excel version). Remember, R is a playground, so have fun exploring and taming those dates!
Bonus Tip: Want to format your dates for readability? Use the format() function, like this:
This will display your dates in the familiar “day/month/year” format.
So there you have it, fellow R enthusiasts! With these tools, you can confidently handle Excel’s date quirks and unleash the power of your data. Happy coding!