简体   繁体   English

如何根据R中的周数计算日期

[英]How to calculate date based on week number in R

I was wondering if there is a way to get the begin of the week date based on a week number in R? 我想知道是否有办法根据R中的周数来获得周日期的开始? For example, if I enter week number = 10, it should give me 9th March, 2014. 例如,如果我输入周数= 10,它应该给我2014年3月9日。

I know how to get the reverse (aka..given a date, get the week number by using as.POSIX functions). 我知道如何获得反向(也就是说...给出一个日期,通过使用as.POSIX函数获取周数)。

Thanks! 谢谢! Prakhar Prakhar

You can try this: 你可以试试这个:

first.day <- as.numeric(format(as.Date("2014-01-01"), "%w"))
week <- 10
as.Date("2014-01-01") + week * 7 - first.day
# [1] "2014-03-09"

This assumes weeks start on Sundays. 假设星期日开始数周。 First, find what day of the week Jan 1 is, then, just add 7 * number of weeks to Jan 1, - the day of week Jan 1 is. 首先,找到1月1日的哪一天,然后,只需将1 *周加到1月1日,即1月1日的星期几。

Note this is slightly different to what you get if you use %W when doing the reverse, as from that perspective the first day of the week seems to be Monday: 请注意,这与您在执行相反操作时使用%W时所获得的略有不同,因为从该角度来看,一周的第一天似乎是星期一:

format(seq(as.Date("2014-03-08"), by="1 day", len=5), "%W %A %m-%d")
# [1] "09 Saturday 03-08"  "09 Sunday 03-09"    "10 Monday 03-10"    "10 Tuesday 03-11"  
# [5] "10 Wednesday 03-12"

but you can adjust the above code easily if you prefer the Monday centric view. 但如果您更喜欢星期一中心视图,则可以轻松调整上述代码。

You may try the ISOweek2date function in package ISOweek . 您可以尝试ISOweek2date封装功能ISOweek

Create a function which takes year, week, weekday as arguments and returns date(s): 创建一个以年,周,工作日为参数并返回日期的函数:

date_in_week <- function(year, week, weekday){
  w <- paste0(year, "-W", sprintf("%02d", week), "-", weekday)
  ISOweek2date(w)
}

date_in_week(year = 2014, week = 10, weekday = 1)
# [1] "2014-03-03"

This date is corresponds to an ISO8601 calendar (see %V in ?strptime ). 此日期对应于?strptime (请参阅?strptime %V )。 I assume you are using the US convention (see %U in ?strptime ). 我假设您使用的是美国惯例(请参阅%U in ?strptime )。 Then some tweeking is needed to convert between ISO8601 and US standard: 然后需要一些tweeking来转换ISO8601和美国标准:

date_in_week(year = 2014, week = 10 + 1, weekday = 1) - 1
# [1] "2014-03-09"

You can enter several weekdays, eg 您可以输入几个工作日,例如

date_in_week(year = 2014, week = 10 + 1, weekday = 1:3) - 1
# [1] "2014-03-09" "2014-03-10" "2014-03-11"

You can accomplish this using the package lubridate 您可以使用包lubridate完成此操作

library(lubridate)
start = ymd("2014-01-01")
#[1] "2014-01-01 UTC"

end = start+10*weeks()
end = end-(wday(end)-1)*days()
#[1] "2014-03-09 UTC"

You can also use strptime to easily get dates from weeks starting on Mondays: 您还可以使用strptime轻松获取周一开始的几周的日期:

first_date_of_week <- function(year, week){
  strptime(paste(year, week, 1), format = "%Y %W %u")
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM