【问题标题】:Extract weeknumber in R using system1 from WEEKNUM function in ms-excel使用 ms-excel 中的 WEEKNUM 函数中的 system1 提取 R 中的星期数
【发布时间】:2018-02-28 05:26:30
【问题描述】:

我想使用与 Excel 中的 WEEKNUM 函数相同的 system 1 在 R 中提取星期数。

请参考下图

我已经探索了从 R 中的日期中提取星期数的所有可用选项,但没有什么能实现我的目标

library(parsedate)
dates =c("12/25/2015", "12/26/2015", "12/27/2015", "12/28/2015", "12/29/2015", "12/30/2015", "12/31/2015", "1/1/2016", "1/2/2016", "1/3/2016", "12/24/2016", "12/26/2016", "12/27/2016", "12/28/2016", "12/29/2016", "12/30/2016", "1/1/2017", "1/2/2017")
#Converting dates into date format in R 
dates = as.Date(parse_date(dates), format = "%Y-%m-%d")

desired_output

52 52 53 53 53 53 53 1 1 2 2 52 53 53 53 53 53 53 1 1

谁能帮我想办法做到这一点。

注意:- 请在将其标记为可能重复之前进行验证。这可能会导致可以提供问题解决方案的人偏离。

【问题讨论】:

  • @RonakShah 它不重复。请确认您的立场。如果我将此应用于“2016-01-03”,那么这将给我 53,而在 excel 中它是 2。
  • @chinsoon12 如果我将此应用于“2017-12-31”,那么它将产生 54 作为输出而不是 53
  • @chinsoon12 似乎工作正常。让我检查并验证我的数据
  • @chinsoon12 我的错。如果我考虑 2017 年 1 月 1 日,这是行不通的。它给出了 2,其中正确的 excel 输出为 1

标签: r excel date week-number


【解决方案1】:

哇,似乎不止是眼前一亮。似乎当 1 月 1 日是星期天(例如 2006-01-01、2012-01-01)时,R 中的 "%U" 对于这些 1 月 1 日的日期给出 "01" 而不是 "00"。下面是一个黑客。

df <- data.frame(dates=as.Date(c(sapply(seq(as.Date("2000-01-01"), by="1 year", length.out=20), function(x) {
    x + -7:7  
})), origin="1970-01-01"))

df$rweeknum <- ifelse(format(as.Date(format(df$dates, "%Y-01-01")), "%a")=="Sun",
    as.integer(strftime(as.Date(df$dates, "%m/%d/%Y"), format = "%U")),
    as.integer(strftime(as.Date(df$dates, "%m/%d/%Y"), format = "%U")) + 1)

#open and check in Excel
write.csv(df, "dates.csv", row.names=FALSE)
shell("dates.csv")

在向 R Core 提出问题之前,需要进一步调查并仔细检查。其他人是否也可以验证您是否有相同的行为? all(format(seq(as.Date("1970-01-01"), by="1 year", length.out=100), "%U")=="00")

【讨论】:

    【解决方案2】:

    这为我提供了所需的输出。 (OP:如果存在未正确处理的边缘情况,请编辑问题以包含它们...)

    设置:

    dates =c("12/25/2015", "12/26/2015", "12/27/2015", 
            "12/28/2015", "12/29/2015", "12/30/2015", "12/31/2015", 
            "1/1/2016", "1/2/2016", "1/3/2016", "1/4/2016", "1/5/2016", 
            "1/6/2016")
    dates = as.Date(dates,format="%m/%d/%Y")
    

    转换:

    as.numeric(format(dates,"%U"))+1
    ## [1] 52 52 53 53 53 53 53  1  1  2  2  2  2
    

    系统信息:

    R version 3.4.3 (2017-11-30)
    Platform: x86_64-apple-darwin15.6.0 (64-bit)
    Running under: OS X El Capitan 10.11.6
    
    locale:
    [1] en_CA.UTF-8/en_CA.UTF-8/en_CA.UTF-8/C/en_CA.UTF-8/en_CA.UTF-8
    

    【讨论】:

    • 感谢您的努力。如果我使用 x = as.Date("2017-01-01") as.numeric(format(x, "%U")) + 1 输出为 2 但所需输出为 1
    • 我已经更新了这个问题。非常感谢您通知应包括边缘情况
    猜你喜欢
    • 1970-01-01
    • 2020-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多