简体   繁体   English

通过 Lubridate 在 R 中使用一年中的一周来获取月份

[英]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.我需要将其转换为2020-Jan, 2020-Jan, 2020-Jan....2020-Feb作为 dataframe 中的一列。 I am using lubridate as a choice.我正在使用lubridate作为选择。

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

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 和 %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.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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