In this article, we are going to get the data between two dates in dataframe in R Programming Language.
We can create a column to store date using as.Date() function
Syntax:
as.Date(‘yyyy-mm-dd’)
Example: Creating dataframe
R
data = data.frame (date= c ( as.Date ( '2020-6-6' ),
as.Date ( '2021-12-1' ),
as.Date ( '2021-11-27' ),
as.Date ( '2020-6-1' ),
as.Date ( '2019-6-6' ),
as.Date ( '2017-12-1' )),
temperature= c (43, 41, 34, 33, 40, 29))
print (data)
|
Output:

We are going to subset the data between date ranges using logical operators. Thus, we need less than(<), greater than(>), and the and(&) operator.
Syntax:
dataframe[dataframe$date_column> “start_date” & dataframe$date_column < “end_date”, ]
where,
- dataframe is the input dataframe
- date_column is the date column in the dataframe
- date is the date specified to get the data from start_date to end_date
Example: R program to get the data from the given date ranges
R
data= data.frame (date= c ( as.Date ( '2020-6-6' ),
as.Date ( '2021-12-1' ),
as.Date ( '2021-11-27' ),
as.Date ( '2020-6-1' ),
as.Date ( '2019-6-6' ),
as.Date ( '2021-10-12' )),
temperature= c (43,41,34,33,40,29))
print (data[data$date > "2021-01-01" & data$date < "2022-10-01" , ])
|
Output:

Example: R program to get the data from the given date ranges
R
data= data.frame (date= c ( as.Date ( '2020-6-6' ),
as.Date ( '2021-12-1' ),
as.Date ( '2021-11-27' ),
as.Date ( '2020-6-1' ),
as.Date ( '2019-6-6' ),
as.Date ( '2017-10-12' )),
temperature= c (43,41,34,33,40,29))
print (data[data$date > "2017-11-11" & data$date < "2019-10-01" , ])
|
Output:

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!