Chris
Chris

Reputation: 3

Having trouble filtering data by date when using variable in R

I have a data frame with a data column. When I filter by date in this way it works fine (I'm brand new at R so apologies for poor terminology or code snippets):

data <- select(full_regression, Date, Tm)
> head(data)
# A tibble: 6 x 2
  Date       Tm   
  <date>     <chr>
1 2021-05-01 CIN  
2 2021-05-01 MIL  
3 2021-05-01 MIN  
4 2021-05-01 OAK  
5 2021-05-01 PHI  
6 2021-05-01 PIT  
> filter_test <- filter(data, Date >= "2021-05-04")
> filter_test
# A tibble: 679 x 2
   Date       Tm   
   <date>     <chr>
 1 2021-05-04 CIN  
 2 2021-05-04 MIN  
 3 2021-05-04 NYY  
 4 2021-05-04 SEA  
 5 2021-05-04 WSN  
 6 2021-05-05 BOS  
 7 2021-05-05 CHC  
 8 2021-05-05 COL  
 9 2021-05-05 KCR  
10 2021-05-05 OAK  
# ... with 669 more rows

I have another table of dates and would like to be able to filter my original data by referencing an element of this dates table but it isn't working.

> head(all_dates)
# A tibble: 6 x 1
  Date      
  <date>    
1 2021-04-01
2 2021-04-02
3 2021-04-03
4 2021-04-04
5 2021-04-05
6 2021-04-06

> test_date <- all_dates[40,]

> test_date
# A tibble: 1 x 1
  Date      
  <date>    
1 2021-05-10

> filter_test2 <- filter(data, Date >= test_date)
    Warning message:
    In mask$eval_all_filter(dots, env_filter) :
      Incompatible methods (">=.Date", "Ops.data.frame") for ">="

Upvotes: 0

Views: 673

Answers (1)

Hobo
Hobo

Reputation: 7611

I think the problem is test_date is a tibble, not a Date. Try

test_date <- all_dates[40, 'Date', drop = TRUE]

instead, which will drop the tibble structure, leaving just the Date.

Upvotes: 4

Related Questions