Raul
Raul

Reputation: 269

Function to filter by week using dplyr

I have a question regarding week selection automation. I currently plot weekly transaccional data using

dat %>%
  filter(week >= 33) %>%
ggplot(aes(date,transaction,group = 1)) +
  geom_line()

Is there a way to create a function which takes the day and subtracts two from the week field to auto populate the previous two weeks? Pseudo code:

If
today() = week 35
then "week" == 35 - 2

dat %>%
  filter(week >= "week" ) %>%
  ggplot(aes(date,transaction,group = 1)) +
  geom_line()

Upvotes: 1

Views: 857

Answers (2)

akrun
akrun

Reputation: 887028

We can use today() from lubridate to get today's date

library(dplyr)
library(ggplot2)
library(lubridate)
todays_week <-  week(today())
dat %>%
      filter(between(week, todays_week - 2, todays_week)) %>%
      ggplot(aes(date,transaction,group = 1)) +
      geom_line() 

Upvotes: 2

Ronak Shah
Ronak Shah

Reputation: 388862

We can use Sys.Date() to get today's date, extract week number from it and filter the data for past 2 weeks.

library(dplyr)
library(ggplot2)
todays_week <- lubridate::week(Sys.Date())

dat %>%
  filter(between(week, todays_week - 2, todays_week)) %>%
  ggplot(aes(date,transaction,group = 1)) +
  geom_line()

Upvotes: 2

Related Questions