问题
I am making a trivial error here but cannot get my head around figuring out what is the problem.
I need to get the date of the Monday of the week of a random date.. Seems I am getting something quite different
mydate <- date("2013-11-05")
format(mydate, "%A") # this is Tuesday, right
#[1] "Tuesday"
month(mydate) # Month November, right
#[1] 11
myyr <- year(mydate); myyr # year is 2013, right
#[1] 2013
day(mydate) # day number is 5, right
#[1] 5
mywk <- isoweek(mydate);mywk # weeknumber is 45, right (yes, not US convention here)
#[1] 45
format(mydate, "%V") # weeknumber is 45, right as well
#[1] "45"
# Monday of week 45 is 2013-11-04 but strptime following gives something else...
strptime(paste0(myyr, "Monday", mywk), "%Y%A%V")
#[1] "2013-11-19 EET"
# and for checking
strptime("2013Monday45","%Y%A%V")
#[1] "2013-11-19 EET"
Thanks in advance
回答1:
Gabor's comment is all you need, essentially. Here is a full function:
mondayForGivenDate <- function(d) {
if (class(d) != "Date") d <- anytime::anydate(d)
d - as.POSIXlt(d)$wday + 1
}
Running this for today (a Saturday), next Monday and previous Saturday gets us three different Monday's as you expect:
R> mondayForGivenDate(Sys.Date())
[1] "2016-11-14"
R> mondayForGivenDate(Sys.Date()+2)
[1] "2016-11-21"
R> mondayForGivenDate(Sys.Date()-7)
[1] "2016-11-07"
R>
The use of the anydate()
function from the anytime is optional but nice because you now get to use many different input formats:
R> mondayForGivenDate(20161119)
[1] "2016-11-14"
R> mondayForGivenDate("20161119")
[1] "2016-11-14"
R> mondayForGivenDate("2016-11-19")
[1] "2016-11-14"
R> mondayForGivenDate("2016-Nov-19")
[1] "2016-11-14"
R>
The key point, once again, is to work with the proper Date
and/or POSIXt
classes in R which almost always give you what is needed -- in this case the wday
component for the day of the week need to revert back to the week's Monday.
来源:https://stackoverflow.com/questions/40696422/r-strptime-monday-date-from-weeknumber-weird