I personally prefer to deal with dates with the R package lubridate
, and filter/subset with dplyr
. If you are dealing with a lot of date-times, the clock
package is also quite handy.
Here's a nice vignette on extracting dates from a date vector with lubridate,
https://cran.r-project.org/web/packages/lubridate/vignettes/lubridate.html
Here's hears info on dplyr's filter package Subset rows using column values — filter • dplyr
With stringr - Dates usually have a consistent separator and format. For example, separating year month and day with a slash or dash. Using only stringr
, there's a nice set of split and substring functions, https://stringr.tidyverse.org/.
library(stringr)
library(dplyr)
date = c("2022-01-01", "2022-01-02")
date %>% str_split_fixed("-", n=3)
#> [,1] [,2] [,3]
#> [1,] "2022" "01" "01"
#> [2,] "2022" "01" "02"
date %>% str_sub(start = 1, end = 4)
#> [1] "2022" "2022"
date %>% str_sub(start = 6, end = 7) %>% as.numeric()
#> [1] 1 1
date %>% str_sub(start = 9, end = 10) %>% as.numeric()
#> [1] 1 2
Created on 2022-04-19 by the reprex package (v2.0.1)