How to have a difference in week units between two

2019-07-21 07:55发布

问题:

I make an example to be clear:

if we speak of 2006/2007, the last day of 2006 was Sunday and the first of 2007 was Monday. According to Italy (but also other countries), they belong to different weeks.

How can I obtain this information in R?

If I do:

difftime(as.Date("2007-01-01"),as.Date("2006-12-31"),units="weeks")

I get: 0.1428571 ...but I would like to know some way to get 1 (as they differ of 1 week)

回答1:

Your problem is that Monday should be the first day of the week. R packages usually consider Sunday to be the first day of the week.

My solution uses the lubridate package and reduces the day of the week by one. With this Mondays become Sundays, the first day of the week for lubridate. I then use floor_date to get the first day of the week and difftime the result.

library(lubridate)
dates <-c(as.Date("2007-01-01"),as.Date("2006-12-31"))
weekdays(dates)
#[1] "Monday" "Sunday"
tempdates <-update(dates,wdays=wday(dates)-1)
weekdays(tempdates)
#[1] "Sunday"   "Saturday"
floor1 <-floor_date(tempdates, "week")
difftime(floor1[1],floor1[2], units = "weeks")
#Time difference of 1 weeks

January 1st and 2nd end up on the same week with this solution

dates <-c(as.Date("2007-01-02"),as.Date("2007-01-01"))
tempdates <-update(dates,wdays=wday(dates)-1)
floor1 <-floor_date(tempdates, "week")
difftime(floor1[1],floor1[2], units = "weeks")
#Time difference of 0 weeks


回答2:

You could start with strftime(as.Date("2007-01-01"),"%U"), which identifies the week number in the year (look up strftime) and add the special case for the last week of a year maybe.



回答3:

The difference in "weeks" depends on whether you are using "week" as 7 days or as a sequence number. This gives you an R method for working with the second definition of "week":

 diff( c(as.numeric(format( as.Date("2007-01-01"), "%W")), 
        as.numeric(format(as.Date("2006-12-31"), "%W")) ))
 [1] 51