How to get week number and year from date in R

10,980

Try this. (Two steps.)

x <- as.Date("1/1/2016", "%d/%m/%Y")
format(x, "%G")
[1] "2015"

format(x, "%V")
[1] "53"

See ?strptime for details.

Share:
10,980
Lili
Author by

Lili

Updated on June 05, 2022

Comments

  • Lili
    Lili almost 2 years

    I am trying to get both week number and year from a date object in R.

    Until then, I did it separately : I used isoweek() function to extract week and year() function to extract year. So that my data.frame has 3 variables : date, week, year

    This is working except for beginning/end of year : for example, 2015 has 53 weeks and January 1st, 2016 belongs to the 53rd week of 2015 ... but with my code, it is such that 1/1/2016 is week 53 but year 2016 whereas I would like it to be week 53 in year 2015.

    So is there a way in R to extract week numbers and years that make sense together ?

    I know there are lots of questions about this but not found anything on this specific beginning/end of year issue.

    Thanks !