问题
I am looking to find the week within a year in R for a list of dates. However, The outputs are rather weird.
See below:
week("2000-01-01")
week("2000-01-06")
week("2000-01-07")
week("2000-01-13")
week("2000-01-14")
This returns 1, 1, 2, 2, 3
However, if you look at a calendar: http://calendars.generalblue.com/content/images/calendars/2000/01-January-2000-Calendar.png
You'd expect it to be 1, 2, 2, 3, 3.
For some reason, this rolls over on a Thursday. Isn't that strange?
Does anyone know how I should do this to get the expected 1, 2, 2, 3, 3 results?
回答1:
Have a look at ?week
Weeks is the number of complete seven day periods that have occured between the date and January 1st, plus one. isoweek returns the week as it would appear in the ISO 8601 system, which uses a reoccuring leap week.
Using the function isoweek you get the following result.
require(lubridate)
dates <- c("2000-01-01","2000-01-06","2000-01-07","2000-01-13","2000-01-14")
sapply(dates, isoweek)
2000-01-01 2000-01-06 2000-01-07 2000-01-13 2000-01-14
52 1 1 2 2
So when does a week "start" for you? In the following date-function a week start's on Sunday
require(lubridate)
my_week <- function(x){
# fst monday of the same year
first_sun <- as.POSIXct(paste0(year(x),"-01-Mon"), format = "%Y-%U-%a")
(yday(x) + (7 - yday(first_sun) + 1)) %/% 7
}
dates <- seq(as.Date("2000-01-01"), as.Date("2000-01-15"), by=1)
a <- sapply(dates, my_week)
names(a) <- dates
> a
2000-01-01 2000-01-02 2000-01-03 2000-01-04 2000-01-05
0 1 1 1 1
2000-01-06 2000-01-07 2000-01-08 2000-01-09 2000-01-10
1 1 1 2 2
2000-01-11 2000-01-12 2000-01-13 2000-01-14 2000-01-15
2 2 2 2 2
来源:https://stackoverflow.com/questions/27116645/r-week-function-returns-unexpected-values