【问题标题】:Using Week of the Year to Get Month via Lubridate in R在 R 中通过 Lubridate 使用一年中的一周来获取月份
【发布时间】:2021-04-23 09:13:42
【问题描述】:

我想从以下数据中的周数中获取月份的名称。

    cov$year_week <- c("2020-01", "2020-02", "2020-03", "2020-04", "2020-05", "2020-06", 
"2020-07", "2020-08", "2020-09", "2020-10")

我需要将其转换为 2020-Jan, 2020-Jan, 2020-Jan....2020-Feb 作为数据框中的一列。我使用lubridate 作为选择。

【问题讨论】:

    标签: r date lubridate


    【解决方案1】:
    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))
    

    注意:月份是我的母语。

    【讨论】:

    • 对不起亲爱的朋友,我的一周是从 0 到 53 全年。所以,我需要得到December 的周数53。当我有几个月而不是几周的数字时,您的代码将起作用。
    • 哦,对不起,让我修复
    • @ambrishdhaka 现在怎么样,你能再看看吗?
    • 谢谢,我猜每个月的周数是固定的,与年份无关。
    • yes lubridate 解决了,如果您的问题得到解决,您可以批准我的回答
    【解决方案2】:

    转换为日期时间

    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"
    

    要获得您想要的结果,您只需要再次调用格式化

    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."
    

    注意:我使用了 %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.
    

    【讨论】:

    • @ambrishdhaka 你可能对%V ... Week of the year as decimal number (01–53) as defined in ISO 8601感兴趣。
    猜你喜欢
    • 2019-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多