Home > other >  Mistake in %Y %U %u format in R
Mistake in %Y %U %u format in R

Time:03-03

I have data that is stored in week and weekdays rather than actual dates. Luckily R has formats but am running into some issues.

Let's take week 8 of 2022 as an example. The week starts at 2022-02-21 and ends at 2022-02-27.

Now in R:

format(as.Date("2022-02-21"), format = "%Y %U %u")
[1] "2022 08 1"

format(as.Date("2022-02-26"), format = "%Y %U %u")
[1] "2022 08 6"

all of this makes sense so far. However when I try for the Sunday it shows me this:

format(as.Date("2022-02-27"), format = "%Y %U %u")
[1] "2022 09 7"

It is as if %U starts the week at Sunday whilst %u starts the week at Monday. Am I using the wrong format?

CodePudding user response:

If your week starts on Monday then you might be looking for:

format(as.Date("2022-02-27"), format = "%Y %W %u")
#> "2022 08 7"

%U returns the week starting on Sunday and %u returns the weekday from 1 to 7 where Monday is 1. %W returns the week starting on Monday and %w returns the weekday from 0 to 6 with Sunday being 0.

  • Related