Home > Blockchain >  subset by date in R within each year
subset by date in R within each year

Time:06-24

My data are as follows:

site year date
A    2019 2019-08-08
A    2019 2019-08-18
A    2019 2019-10-14
A    2019 2019-10-27
B    2019 2019-08-07
B    2019 2019-08-19
B    2019 2019-10-15
B    2019 2019-10-20
A    2020 2020-08-08
A    2020 2020-08-18
A    2020 2020-10-14
A    2020 2020-10-27
B    2020 2020-08-07
B    2020 2020-08-19
B    2020 2020-10-15
B    2020 2020-10-20

For each year, I would like to subset rows that fulfill the following conditions:

=<October 15 and >=August 15

Thank you in advance!

CodePudding user response:

Convert to yearday and use filter

library(dplyr)
library(lubridate)
df1 %>% 
  mutate(date = ymd(date)) %>% 
  filter(between(yday(date), 228, 289))

-output

 site year       date
1    A 2019 2019-08-18
2    A 2019 2019-10-14
3    B 2019 2019-08-19
4    B 2019 2019-10-15
5    A 2020 2020-08-18
6    A 2020 2020-10-14
7    B 2020 2020-08-19
8    B 2020 2020-10-15

data

df1 <- structure(list(site = c("A", "A", "A", "A", "B", "B", "B", "B", 
"A", "A", "A", "A", "B", "B", "B", "B"), year = c(2019L, 2019L, 
2019L, 2019L, 2019L, 2019L, 2019L, 2019L, 2020L, 2020L, 2020L, 
2020L, 2020L, 2020L, 2020L, 2020L), date = c("2019-08-08", "2019-08-18", 
"2019-10-14", "2019-10-27", "2019-08-07", "2019-08-19", "2019-10-15", 
"2019-10-20", "2020-08-08", "2020-08-18", "2020-10-14", "2020-10-27", 
"2020-08-07", "2020-08-19", "2020-10-15", "2020-10-20")), 
class = "data.frame", row.names = c(NA, 
-16L))
  • Related