Get startedGet started for free

Comparing intervals and datetimes

A common task with intervals is to ask if a certain time is inside the interval or whether it overlaps with another interval.

The operator %within% tests if the datetime (or interval) on the left hand side is within the interval of the right hand side. For example, if y2001 is the interval covering the year 2001,

y2001 <- ymd("2001-01-01") %--% ymd("2001-12-31")

Then ymd("2001-03-30") %within% y2001 will return TRUE and ymd("2002-03-30") %within% y2001 will return FALSE.

int_overlaps() performs a similar test, but will return true if two intervals overlap at all.

Practice to find out which monarchs saw Halley's comet around 1066.

This exercise is part of the course

Working with Dates and Times in R

View Course

Exercise instructions

We've put halleys a data set describing appearances of Halley's comet in your workspace.

  • Print halleys to examine the date. perihelion_date is the date the Comet is closest to the Sun. start_date and end_date are the range of dates the comet is visible from Earth.
  • Create a new column, visible, that is an interval from start_date to end_date.
  • You'll work with one appearance, extract the 14th row of halleys.
  • Filter monarchs to those where halleys_1066$perihelion_date is within reign.
  • Filter monarchs to those where halleys_1066$visible overlaps reign.

Hands-on interactive exercise

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

# Print halleys
halleys

# New column for interval from start to end date
halleys <- halleys %>% 
  mutate(visible = ___)

# The visitation of 1066
halleys_1066 <- halleys[__, ] 

# Monarchs in power on perihelion date
monarchs %>% 
  filter(___) %>%
  select(name, from, to, dominion)

# Monarchs whose reign overlaps visible time
monarchs %>% 
  filter(___) %>%
  select(name, from, to, dominion)
Edit and Run Code