Practice rounding

As you saw in the video, round_date() rounds a date to the nearest value, floor_date() rounds down, and ceiling_date() rounds up.

All three take a unit argument which specifies the resolution of rounding. You can specify "second", "minute", "hour", "day", "week", "month", "bimonth", "quarter", "halfyear", or "year". Or, you can specify any multiple of those units, e.g. "5 years", "3 minutes" etc.

Try them out with the release datetime of R 3.4.1.

This exercise is part of the course

Working with Dates and Times in R

View Course

Exercise instructions

  • Choose the right function and units to round r_3_4_1 down to the nearest day.
  • Choose the right function and units to round r_3_4_1 to the nearest 5 minutes.
  • Choose the right function and units to round r_3_4_1 up to the nearest week.
  • Find the time elapsed on the day of release at the time of release by subtracting r_3_4_1 rounded down to the day from r_3_4_1.

Hands-on interactive exercise

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

r_3_4_1 <- ymd_hms("2016-05-03 07:13:28 UTC")

# Round down to day
___(r_3_4_1, unit = ___)

# Round to nearest 5 minutes
___(r_3_4_1, unit = ___)

# Round up to week 
___(r_3_4_1, unit = ___)

# Subtract r_3_4_1 rounded down to day
r_3_4_1 - ___(r_3_4_1, unit = ___)