Get Started

Calculations with Dates

Both Date and POSIXct R objects are represented by simple numerical values under the hood. This makes calculation with time and date objects very straightforward: R performs the calculations using the underlying numerical values, and then converts the result back to human-readable time information again.

You can increment and decrement Date objects, or do actual calculations with them:

today <- Sys.Date()
today + 1
today - 1

as.Date("2015-03-12") - as.Date("2015-02-27")

To control your eating habits, you decided to write down the dates of the last five days that you ate pizza. In the workspace, these dates are defined as five Date objects, day1 to day5. A vector pizza containing these 5 Date objects has been pre-defined for you.

This is a part of the course

“Intermediate R”

View Course

Exercise instructions

  • Calculate the number of days that passed between the last and the first day you ate pizza. Print the result.
  • Use the function diff() on pizza to calculate the differences between consecutive pizza days. Store the result in a new variable day_diff.
  • Calculate the average period between two consecutive pizza days. Print the result.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# day1, day2, day3, day4 and day5 are already available in the workspace

# Difference between last and first pizza day


# Create vector pizza
pizza <- c(day1, day2, day3, day4, day5)

# Create differences between consecutive pizza days: day_diff


# Average period between two consecutive pizza days

This exercise is part of the course

Intermediate R

BeginnerSkill Level
4.5+
131 reviews

Continue your journey to becoming an R ninja by learning about conditional statements, loops, and vector functions.

Mastering R programming is not only about understanding its programming concepts. Having a solid understanding of a wide range of R functions is also important. This chapter introduces you to many useful functions for data structure manipulation, regular expressions, and working with times and dates.

Exercise 1: Useful FunctionsExercise 2: Mathematical utilitiesExercise 3: Find the errorExercise 4: Data UtilitiesExercise 5: Find the error (2)Exercise 6: Beat Gauss using RExercise 7: Regular ExpressionsExercise 8: grepl & grepExercise 9: grepl & grep (2)Exercise 10: sub & gsubExercise 11: sub & gsub (2)Exercise 12: Times & DatesExercise 13: Right here, right nowExercise 14: Create and format datesExercise 15: Create and format timesExercise 16: Calculations with Dates
Exercise 17: Calculations with TimesExercise 18: Time is of the essence

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free