簡體   English   中英

如何從R中的年和周號中獲取月中的月和周?

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

我有一個包含年份和年份的列,我需要該列中月份的月份和周號,我們將不勝感激。

我有x,我需要的是y和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

這是我嘗試過的

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

這是dplyr解決方案

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

注意:這假設year-weekno日期是指每周的第一天。


或以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

@ maurits-evers的回答很簡潔,而我獨立於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
                 )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM