Home > Back-end >  select the last 30 days of POSIXct dates in R
select the last 30 days of POSIXct dates in R

Time:07-01

Probably simple, but this is my first time working with POSIXct date format.

I have a table of orders (that i got from a syl database) and I would like to select all rows of the last 30 days. so today's date minus 30 days. my date is of the type POSIXct.

Now, I know how to do this selection in sql, but need to do this in R. Any suggestions?

It is not a requirement to keep the POSIXct format, one could also transform into another time format if this makes the selection easier.

Side note: the R-code will later on be embedded into a MS SQL environment.

CodePudding user response:

library(tidyverse)
library(lubridate)

df <- tibble(
  dates = seq(today() %m-% months(3), 
              today(), by = "days"), 
  data = sample(40:400, 93, replace = TRUE)
)

df
#> # A tibble: 93 x 2
#>    dates       data
#>    <date>     <int>
#>  1 2022-03-30   369
#>  2 2022-03-31   392
#>  3 2022-04-01    53
#>  4 2022-04-02   256
#>  5 2022-04-03   299
#>  6 2022-04-04   372
#>  7 2022-04-05   212
#>  8 2022-04-06   244
#>  9 2022-04-07    97
#> 10 2022-04-08   394
#> # ... with 83 more rows

df %>%  
  filter(dates >= today() %m-% days(30))

#> # A tibble: 31 x 2
#>    dates       data
#>    <date>     <int>
#>  1 2022-05-31   157
#>  2 2022-06-01   274
#>  3 2022-06-02   139
#>  4 2022-06-03   231
#>  5 2022-06-04   251
#>  6 2022-06-05   343
#>  7 2022-06-06   187
#>  8 2022-06-07   118
#>  9 2022-06-08    90
#> 10 2022-06-09   171
#> # ... with 21 more rows
  # filter dates that is larger than today - 30 days

Created on 2022-06-30 by the reprex package (v2.0.1)

  • Related