Looking for a function in R to convert dates into week numbers (of year) I went for week
from package data.table
. However, I observed some strange behaviour:
> week("2014-03-16") # Sun, expecting 11 [1] 11 > week("2014-03-17") # Mon, expecting 12 [1] 11 > week("2014-03-18") # Tue, expecting 12 [1] 12
Why is the week number switching to 12 on tuesday, instead of monday? What am I missing? (Timezone should be irrelevant as there are just dates?!)
Other suggestions for (base) R functions are appreciated as well.
To find out how many weeks there are between two dates, you can use the DATEDIF function with "D" unit to return the difference in days, and then divide the result by 7. Where A2 is the start date and B2 is the end date of the period you are calculating.
=INT((DAY(B5)-1)/7)+1 Here, first using the DAY function we get the value of a day of the date in Cell B5. Then, we subtracted the value by 1 and divided it by 7 to get the day into the week number of the month.
Base package
Using the function strftime
passing the argument %V
to obtain the week of the year as decimal number (01–53) as defined in ISO 8601. (More details in the documentarion: ?strftime)
strftime(c("2014-03-16", "2014-03-17","2014-03-18", "2014-01-01"), format = "%V")
Output:
[1] "11" "12" "12" "01"
if you try with lubridate:
library(lubridate) lubridate::week(ymd("2014-03-16", "2014-03-17","2014-03-18", '2014-01-01')) [1] 11 11 12 1
The pattern is the same. Try isoweek
lubridate::isoweek(ymd("2014-03-16", "2014-03-17","2014-03-18", '2014-01-01')) [1] 11 12 12 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With