Home > Net >  r - Filter a rows by a date that alters each day
r - Filter a rows by a date that alters each day

Time:09-26

The dataset is 1 column with thousands of rows that contain a date as "2021-09-23T06:38:53.458Z".

With the following code I am able to subset the rows from yesterday:

rows_from_yesterday <- df[df$timestamp %like% "2021-09-24", ] 

It works like a charm! I would now like to automate the process because I am not able to update the match criteria each day. How would one approach this? Any tips or suggestions?

Just to be clear. I would like that the "2021-09-24" is automatically updated to "2021-09-25" when it is tomorrow. I have tried the following:

rows_from_yesterday <- df[df$timestamp %like% as.character(Sys.Date()-1), ] 

This is sadly without succes.

CodePudding user response:

If I understood you want to filter the observations from yesterday, right? If so, here a solution:

library(dplyr)
library(lubridate)

x <- "2021-09-23T06:38:53.458Z"

df <- tibble(timestamp = x)

df %>% 
  mutate(timestamp = ymd_hms(timestamp)) %>% 
  #filter dates equals to yesterday
  filter(as_date(timestamp) == (today()-days(1)))
  • Related