How to Subset by a Date Range in R (With Examples)


The easiest way to subset a data frame by a date range in R is to use the following syntax:

df[df$date >= "some date" & df$date <= "some date", ]

This tutorial provides several examples of how to use this function in practice.

Example 1: Subset Between Two Dates

The following code shows how to select the rows of a data frame that fall between two dates, inclusive:

#make this example reproducible
set.seed(0)

#create data frame
df <- data.frame(date = as.Date("2021-01-01") - 0:19,
                 sales = runif(20, 10, 500) + seq(50, 69)^2)

#view first six rows
head(df)

        date    sales
1 2021-01-01 2949.382
2 2020-12-31 2741.099
3 2020-12-30 2896.341
4 2020-12-29 3099.698
5 2020-12-28 3371.022
6 2020-12-27 3133.824

#subset between two dates, inclusive
df[df$date >= "2020-12-25" & df$date <= "2020-12-28", ]

        date    sales
5 2020-12-28 3371.022
6 2020-12-27 3133.824
7 2020-12-26 3586.211
8 2020-12-25 3721.891

You only need to modify the greater and less than signs to select the rows that fall between two dates, exclusive:

#make this example reproducible
set.seed(0)

#create data frame
df <- data.frame(date = as.Date("2021-01-01") - 0:19,
                 sales = runif(20, 10, 500) + seq(50, 69)^2)

#subset between two dates, exclusive
df[df$date > "2020-12-25" & df$date < "2020-12-28", ]

        date    sales
6 2020-12-27 3133.824
7 2020-12-26 3586.211

Example 2: Subset After a Certain Date

The following code shows how to select the rows of a data frame that occur after a certain date:

#make this example reproducible
set.seed(0)

#create data frame
df <- data.frame(date = as.Date("2021-01-01") - 0:19,
                 sales = runif(20, 10, 500) + seq(50, 69)^2)

#subset after a certain date
df[df$date >= "2020-12-22", ]

         date    sales
1  2021-01-01 2949.382
2  2020-12-31 2741.099
3  2020-12-30 2896.341
4  2020-12-29 3099.698
5  2020-12-28 3371.022
6  2020-12-27 3133.824
7  2020-12-26 3586.211
8  2020-12-25 3721.891
9  2020-12-24 3697.791
10 2020-12-23 3799.266
11 2020-12-22 3640.275

Example 3: Subset Before a Certain Date

The following code shows how to select the rows of a data frame that occur before a certain date:

#make this example reproducible
set.seed(0)

#create data frame
df <- data.frame(date = as.Date("2021-01-01") - 0:19,
                 sales = runif(20, 10, 500) + seq(50, 69)^2)

#subset before a certain date
df[df$date < "2020-12-22", ]

         date    sales
12 2020-12-21 3831.928
13 2020-12-20 3940.513
14 2020-12-19 4315.641
15 2020-12-18 4294.211
16 2020-12-17 4612.222
17 2020-12-16 4609.873
18 2020-12-15 4850.633
19 2020-12-14 5120.034
20 2020-12-13 4957.217

Additional Resources

How to Plot a Time Series in R
How to Extract Year from Date in R
How to Aggregate Daily Data to Monthly and Yearly in R

Leave a Reply

Your email address will not be published.