Praveen Chougale
Praveen Chougale

Reputation: 383

How to get month and week of the month from year and week no in R?

I have a column with year and week of the year.I need month and week no of the month from that column.Any help would be highly appreciated.

I have x,what I need is y and z.

x          y(month of the year)             z (week number of that month)
2016-11      3                                        3
2016-12      3                                        4
2018-01      1                                        1 
2019-10      3                                        2

This is what I tried

as.Date(paste(x,sep=""),"%Y%U%u")

Upvotes: 0

Views: 580

Answers (2)

Maurits Evers
Maurits Evers

Reputation: 50678

Here is a dplyr solution

library(dplyr)
df %>%
    mutate(
        x = as.POSIXct(strptime(paste0(x, "-1"), format = "%Y-%W-%u")),
        y = format(x, "%m"),
        z = 1 + as.integer(format(x, "%d")) %/% 7)
#           x  y z
#1 2016-03-14 03 3
#2 2016-03-21 03 4
#3 2018-01-01 01 1
#4 2019-03-11 03 2

Note: This assumes that the year-weekno dates refer to the first day of every week.


Or in base R

transform(
    transform(df, x = as.POSIXct(strptime(paste0(x, "-1"), format = "%Y-%W-%u"))),
    y = format(x, "%m"),
    z = 1 + as.integer(format(x, "%d")) %/% 7)
#           x  y z
#1 2016-03-14 03 3
#2 2016-03-21 03 4
#3 2018-01-01 01 1
#4 2019-03-11 03 2

Upvotes: 4

pzhao
pzhao

Reputation: 335

The answer by @maurits-evers is neat, while I rewrote it independently from dplyr:

x <- c('2016-11', '2016-12', '2018-01', '2019-10')
x2 <- strptime(paste(x, "1"), format = "%Y-%W %u")
yw <- data.frame(x = x,
                 y = as.integer(format(x2, '%m')),
                 z = as.integer(format(x2, "%d")) %/% 7 + 1
                 )

Upvotes: 1

Related Questions