Extract Data Frame Rows by Dates in R (Example Code)
In this tutorial, I’ll illustrate how to select data frame rows in a particular date range in R.
Creation of Example Data
my_df <- data.frame(Date = c("2021-11-12", "2023-05-13", "2027-11-15", # Example data "2029-01-12", "2012-11-11", "2022-10-18", "2020-05-22", "2022-07-14", "2023-11-15"), Value = letters[1:9]) my_df # Show example data # Date Value # 1 2021-11-12 a # 2 2023-05-13 b # 3 2027-11-15 c # 4 2029-01-12 d # 5 2012-11-11 e # 6 2022-10-18 f # 7 2020-05-22 g # 8 2022-07-14 h # 9 2023-11-15 i |
my_df <- data.frame(Date = c("2021-11-12", "2023-05-13", "2027-11-15", # Example data "2029-01-12", "2012-11-11", "2022-10-18", "2020-05-22", "2022-07-14", "2023-11-15"), Value = letters[1:9]) my_df # Show example data # Date Value # 1 2021-11-12 a # 2 2023-05-13 b # 3 2027-11-15 c # 4 2029-01-12 d # 5 2012-11-11 e # 6 2022-10-18 f # 7 2020-05-22 g # 8 2022-07-14 h # 9 2023-11-15 i
Example: Convert Character to Date & Extract Data Frame Subset
my_df$Date <- as.Date(my_df$Date) # Converting column to Date class |
my_df$Date <- as.Date(my_df$Date) # Converting column to Date class
my_df[my_df$Date >= "2020-10-01" & my_df$Date <= "2026-12-01", ] # Date range # Date Value # 1 2021-11-12 a # 2 2023-05-13 b # 6 2022-10-18 f # 8 2022-07-14 h # 9 2023-11-15 i |
my_df[my_df$Date >= "2020-10-01" & my_df$Date <= "2026-12-01", ] # Date range # Date Value # 1 2021-11-12 a # 2 2023-05-13 b # 6 2022-10-18 f # 8 2022-07-14 h # 9 2023-11-15 i
Related Tutorials
Have a look at the following R programming tutorials: