Reputation: 749
I want to get the name of the month from the week number from the following data.
cov$year_week <- c("2020-01", "2020-02", "2020-03", "2020-04", "2020-05", "2020-06",
"2020-07", "2020-08", "2020-09", "2020-10")
I need to convert it as 2020-Jan, 2020-Jan, 2020-Jan....2020-Feb
as a column in dataframe. I am using lubridate
as a choice.
Upvotes: 0
Views: 125
Reputation: 10385
Converting to datetime
cov <- c("2020-01", "2020-02", "2020-03", "2020-04", "2020-05", "2020-06",
"2020-07", "2020-08", "2020-09", "2020-10")
strptime(paste0(cov,"-1"),"%Y-%W-%w")
[1] "2020-01-06 CET" "2020-01-13 CET" "2020-01-20 CET" "2020-01-27 CET" "2020-02-03 CET"
[6] "2020-02-10 CET" "2020-02-17 CET" "2020-02-24 CET" "2020-03-02 CET" "2020-03-09 CET"
To get your desired result you just need another call to format
format(strptime(paste0(cov,"-1"),"%Y-%W-%w"),"%Y-%b")
[1] "2020-jan." "2020-jan." "2020-jan." "2020-jan." "2020-feb." "2020-feb." "2020-feb."
[8] "2020-feb." "2020-mar." "2020-mar."
Note: I used %W and %w
%w
Weekday as decimal number (0–6, Sunday is 0).
%W
Week of the year as decimal number (00–53) using Monday as the first day of week (and typically with the first Monday of the year as day 1 of week 1). The UK convention.
Upvotes: 1
Reputation: 2690
library(lubridate)
library(tidyverse)
dummy <- data.frame(dumcol =seq.Date(as.Date('2020-01-01'),as.Date('2020-12-31'),by='week'))
dummy %>%
mutate(week=week(dumcol),months=month(dumcol,label=T)) %>%
select(week,months)-> dummy
cov %>%
select(year_week) %>%
separate(year_week,c('year','week')) %>%
mutate(week=as.numeric(week)) %>%
left_join(dummy,by='week') %>%
mutate(new_col=paste0(year,'-',months))
note : months are in my native language.
Upvotes: 1