how do I filter a R data frame by year?
In the reproducible example I am trying to filter dates that are in 2021 (in column b). Thank you!
library(tidyverse)
a <- c(10,20,30)
b <- as.Date(c('31-11-20', '15-11-21', '31-11-22'))
my_df <- data.frame(a,b)
I have tried the following code but none of them successfully filtered by the year 2021.
my_df_new <- my_df %>%
filter(between(b, as.Date('01-01-21'), as.Date('31-12-21')))
my_df_new <- my_df %>%
filter(between(b, as.Date('2021-01-01'), as.Date('2021-12-31')))
my_df_new <- my_df[my_df$b > "31-12-20" & my_df$b < "1-01-22", ]
my_dfare in this millenium. Have you looked at your data and recognized that"31-11-20"is being parsed into"0031-11-20"? You really need to fix that before you think about how to filter it. - r2evansas.Date(..., format="%d-%m-%Y"), your middle code works. - r2evans31-11-20is being treated as November 20, 0031 when you want it to be treated as November 31, 2020 presumably. - socialscientist