Home > Net >  DPLYR filter by max date and max date - 7 in R
DPLYR filter by max date and max date - 7 in R

Time:11-05

In R,

%>%
  filter(SpecimenDate >= as.Date("2021-10-25") & SpecimenDate <= as.Date("2021-10-31"))

Provides a manual filter and

%>%
  filter(date == max(date))

Filters to the most recent date of data within a table only.

Can anyone advise please how to create a filter that sorts between max(date)) and max(date))-7 (i.e. all values within most recent 7 days)?

I've attempted the below which leads to Error: Problem with filter() input ..1. i Input ..1 is date >= max(date) & date <= max(date - 7). x non-numeric argument to binary operator

filter(date >= max(date) & date <= max(date-7)

Thank you.

CodePudding user response:

To filter for the data between the most recent day as well as the 7 days' before it, you only need one condition:

filter(date >= (max(date) - 7))


Just so there's a reproducible example (that anyone can run), this demonstrates the same concept, but using the inbuilt iris dataset

iris %>% 
  filter(Petal.Length < (max(Petal.Length) - 2))

CodePudding user response:

Does this work:

df <- data.frame(c1 = 1:15,
                 c2 = seq.Date(Sys.Date()-14, Sys.Date(), by = 1))
df %>% filter(between(c2, max(c2)-7, max(c2)))
  c1         c2
1  8 2021-10-28
2  9 2021-10-29
3 10 2021-10-30
4 11 2021-10-31
5 12 2021-11-01
6 13 2021-11-02
7 14 2021-11-03
8 15 2021-11-04

CodePudding user response:

You should check str of your data, and please provide reproducible example.

dummy <- data.frame(date = seq.Date(as.Date("2020-01-01"), as.Date("2020-01-15"), by = "day"))

If it's not Date format, It will give that error.

dummy %>%
  mutate(date = as.character(date))%>%
  filter(date >= max(date) & date <= max(date-7))
Error: Problem with `filter()` input `..1`.
i Input `..1` is `date >= max(date) & date <= max(date - 7)`.
x non-numeric argument to binary operator

As your condition is pretty weird, that

dummy %>%
  mutate(date = as.Date(date))%>%
  filter(date >= max(date) & date <= max(date-7))
         

this will return empty dataframe, but will not reproduce your error.

CodePudding user response:

Here's one way to achieve what you are after:

library(tidyverse)

dates <- tibble(
  date = seq(as.Date("2021-10-01"), by = "day", length.out = 20))

dates %>% 
  filter(date <= max(date) & date >= max(date) - 7)
#> # A tibble: 8 × 1
#>   date      
#>   <date>    
#> 1 2021-10-13
#> 2 2021-10-14
#> 3 2021-10-15
#> 4 2021-10-16
#> 5 2021-10-17
#> 6 2021-10-18
#> 7 2021-10-19
#> 8 2021-10-20

Created on 2021-11-04 by the reprex package (v2.0.1)

CodePudding user response:

I would use an interval condition.

    data %>% filter(date %in% (max(date)-7):max(date))

This should work!

  • Related