简体   繁体   中英

Using Week of the Year to Get Month via Lubridate in R

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM