B.Chellali
B.Chellali

Reputation: 33

Convert week.year to year.month - date in R

I would like to convert a date week.year ("44.2016") to year.month (2016-11) in ISO 8601

I have a variable date_week <- "44.2016"

I tried this :

as.Date(date_week, format = "%U.%Y")

as.Date(date_week, format = "%W.%Y")

I have this result: "2016-02-21"

I also tried this :

as.Date(date_week, format = "%w.%Y")

as.Date(date_week, format = "%w.%Y")

result : NA

I would like to have this RESULT : "2016-11"

Thanks for your help !

Upvotes: 2

Views: 953

Answers (1)

nghauran
nghauran

Reputation: 6768

Note that you need to specify a day since a week can imply two consecutive months. Try this:

as.Date(paste("1", date_week, sep = "."), format = "%w.%W.%Y") # 1st day (monday 31 oct 2016)
as.Date(paste("2", date_week, sep = "."), format = "%w.%W.%Y") # 2nd day (Tuesday 01 nov 2016)
# new format 
format(as.Date(paste("1", date_week, sep = "."), format = "%w.%W.%Y"), "%Y-%m")
# [1] "2016-10"
format(as.Date(paste("2", date_week, sep = "."), format = "%w.%W.%Y"), "%Y-%m")
# [1] "2016-11"

Upvotes: 5

Related Questions