如何在两天之间的星期单位有差异(即使他们很近,但属于不同的星期) [英] How to have a difference in week units between two days (even if they're close but belong to different weeks)

查看:142
本文介绍了如何在两天之间的星期单位有差异(即使他们很近,但属于不同的星期)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

举例说明:



如果我们说2006/2007,2006年的最后一天是星期日,2007年的第一天是星期一。
根据意大利(还有其他国家),它们属于不同的星期。



如何在R中获取此信息?



如果我这样做:

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

我得到:0.1428571
...但我想知道一些方法来获得1(因为他们不同1周)

解决方案

你的问题是星期一应该是一星期的第一天。 R包通常认为星期天是一星期的第一天。



我的解决方案使用 lubridate 包,并将星期几减少一个。星期一成为星期日, lubridate 的星期一。然后使用 floor_date 获得一周的第一天,并且 difftime 结果。

 库(lubridate)
日期< -c(as.Date(2007-01-01) ,as.Date(2006-12-31))
工作日(日期)
#[1]星期一星期日
tempdates< -update(dates,wdays = wday(日期)-1)
平日(tempdates)
#[1]星期日星期六
floor1< -floor_date(tempdates,week)
difftime (floor1 [1],floor1 [2],units =weeks)
#1个月的差距

1月1日和2日结束在同一周与这个解决方案

 日期< -c(as 。日期(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)
#0个星期的时差


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)

解决方案

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

这篇关于如何在两天之间的星期单位有差异(即使他们很近,但属于不同的星期)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆