Zhiqiang Wang
Zhiqiang Wang

Reputation: 6769

lubridate::floor_date(x, "14 days"): how to prevent restart with a new month?

I am grouping multiple days using lubridate::floor_data, but it restart grouping with a new month. Is this alternative to stop this?

floor_date(x, "7 days") always start with the first day of each month. I want it to be the same as floor_date(x, "week")

Using the data from https://r4ds.had.co.nz/dates-and-times.html

flights_dt %>% 
mutate(
week = floor_date(dep_time, "week"), 
day7  = floor_date(dep_time, "7 days"),
day14 = floor_date(dep_time, "14 days")) 

I want day7 and day14 to continue from previous time, not restart from the first day of the month.

Upvotes: 2

Views: 597

Answers (2)

Zhiqiang Wang
Zhiqiang Wang

Reputation: 6769

I think I might have worked out a solution:

df1<-flights_dt %>% 
mutate(
dep_date = as_date(dep_time), 
date_14days = dmy(01012013) + floor(((dep_date) - dmy(01012013))/14)*14)

Upvotes: 1

cicero
cicero

Reputation: 528

One way to solve this is to attribute to a date the day number of the year. You can do this with the package lubridate:

output <- flights_dt %>% mutate(day_nb = lubridate::yday(deptime)

Then to group by period of X days, you need to calculate the euclidean division of the day number by X :

output %>% mutate(group_7_days = day_nb %/% 7,
                  group_14_days = day_nb %/% 14)

Then you can just group by these new columns to have your data per period of 7/14 days

Upvotes: 1

Related Questions