【问题标题】:How to get month and week of the month from year and week no in R?如何从 R 中的年份和周数中获取月份的月份和周数?
【发布时间】:2019-05-10 07:07:55
【问题描述】:

我有一列包含一年中的年份和星期。我需要该列中的月份和星期。任何帮助将不胜感激。

我有 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")

【问题讨论】:

  • 你检查过lubridateweekmonth等函数吗?
  • 是的,我没有得到预期的结果
  • 这些年-周日期对应于哪一天?总是那一周的第一天吗?最后一个?
  • 每个月的星期一

标签: r date


【解决方案1】:

这是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

【讨论】:

  • @pzhao 我想这归结为个人喜好。我通常更喜欢dplyr/tidyverse 语法而不是基本 R。但我添加了一个使用 transform 的仅限基本 R 的解决方案。
  • 谢谢。应该注意的是,这个解决方案是周计数的混合。 %W 使用星期一作为一年中一周的开始,而 %d / 7 使用一个月的第一天作为该月一周的开始。问题本身并没有定义它。
【解决方案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
                 )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-25
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 2012-06-06
    • 2019-07-27
    • 2013-06-23
    相关资源
    最近更新 更多