Skip to Tutorial Content

Filtering Dates with Lubridate

We will start with the covid dataset, and filteR for observations on particular dates.

Exercise 1

Write the R code required to filter the covid_dates dataset to rows with a fake_date of April 7, 2020.

covid_dates %>%
  select(subject_id, fake_date) %>%
  filter(---)
covid_dates %>%
  select(subject_id, fake_date) %>%
  filter(fake_date == ymd("2020-04-07"))

Exercise 2

Write the R code required to filter the covid_dates dataset to rows with a fake_date between March 10, 2020, and March 17, 2020.

covid_dates %>%
  select(subject_id, fake_date) %>%
  filter(---)
covid_dates %>%
  select(subject_id, fake_date) %>%
  filter(between(fake_date, ---, ---)) %>%
  arrange(fake_date)
covid_dates %>%
  select(subject_id, fake_date) %>%
  filter(between(fake_date, ymd(---), ymd(---))) %>%
  arrange(fake_date)
covid_dates %>%
  select(subject_id, fake_date) %>%
  filter(between(fake_date, ymd("2020-03-10"), ymd("2020-03-17"))) %>%
  arrange(fake_date)

Exercise 3

Write the R code required to filter the bmt_dates dataset to rows with a fake_avghd_date after a date two years before June 1, 2020.

bmt_dates %>%
  select(id, fake_agvhd_date) %>%
  filter(---)
bmt_dates %>%
  select(id, fake_agvhd_date) %>%
  filter(fake_agvhd_date >
           today() -   ---)
bmt_dates %>%
  select(id, fake_agvhd_date) %>%
  filter(fake_agvhd_date >
           ymd("2020-06-30") - years(2))

Exercise 4

Write the R code required to filter the bmt_dates dataset to subjects with a fake_bmt_date on a Wednesday (the 4th weekday). You should get 11 observations.

bmt_dates %>%
  select(id, fake_bmt_date) %>%
  filter(---)
bmt_dates %>%
  select(id, fake_bmt_date) %>%
  filter(wday(fake_bmt_date) == 4)

Exercise 5

Write the R code required to filter the bmt_dates dataset to subjects who had a bone marrow transplant between January 1, 2017 and December 31, 2020.

bmt_dates %>%
  select(id, fake_bmt_date) %>%
  filter(---) %>%
  arrange(fake_bmt_date)
bmt_dates %>%
  select(id, fake_bmt_date) %>%
  filter(---) %>%
  arrange(fake_bmt_date)
bmt_dates %>%
  select(id, fake_bmt_date) %>%
  filter(between(fake_bmt_date, ymd("2017-01-01"), ymd("2020-12-31"))) %>%
  arrange(fake_bmt_date)

Tutorial