【问题标题】:Why do I get the wrong date back when I format a tsibble yearweek object back to year month day (yearweek "2020 W01" formats to "2020-12-30")当我将 tsibble yearweek 对象格式化回年月日时,为什么我会得到错误的日期(年周“2020 W01”格式为“2020-12-30”)
【发布时间】:2021-05-12 22:00:01
【问题描述】:
library(tsibble)
#> 
#> Attaching package: 'tsibble'
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, union

(yw <- yearweek("2020-01-01"))
#> <yearweek[1]>
#> [1] "2020 W01"
#> # Week starts on: Monday
format(yw, "%Y-%m-%d")
#> [1] "2020-12-30"

reprex package (v2.0.0) 于 2021-05-12 创建

【问题讨论】:

    标签: r format tsibble


    【解决方案1】:

    因为它按照记录的方式运行。在help(strptime) 下使用base R 中的精细文档:

     ‘%U’ Week of the year as decimal number (00-53) using Sunday as    
          the first day 1 of the week (and typically with the first     
          Sunday of the year as day 1 of week 1).  The US convention.        
    
     ‘%V’ Week of the year as decimal number (01-53) as defined in ISO 
          8601.  If the week (starting on Monday) containing 1 January 
          has four or more days in the new year, then it is considered 
          week 1.  Otherwise, it is the last week of the previous year,
          and the next week is week 1.  (Accepted but ignored on       
          input.)                                                      
                                                                       
     [...]      
    
     ‘%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.      
    

    然后我们可以使用%Y-W 进行测试,然后选择:

    > strftime(as.Date("2020-01-01"), "%Y-W%U")      
    [1] "2020-W00"                                
    > strftime(as.Date("2020-01-01"), "%Y-W%V")   
    [1] "2020-W01"                                
    > strftime(as.Date("2020-01-01"), "%Y-W%W")   
    [1] "2020-W00"                                
    > 
    

    您在示例中得到的基本上只是相同功能的包装。也许yearweek() 给你一个约定的选择;如果不是,您现在知道如何在不同的选项下构建自己的。

    【讨论】:

    • 我认为问题是为什么strftime(yw, "%Y-%m-%d")返回2019-12-30这是可以理解的,而format(yw,"%Y-%m-%d")返回2020-12-30,为什么相差1年?
    • 不知道——也许format() 发送到yearweek 到别的地方。我倾向于使用基本的 R 函数。但是请参阅帮助页面中的%G:“以周为基础的年份(请参阅‘%V’)作为十进制数。”
    • 是的,Waldi 了解我的问题,因为格式我得到了一整年的不同。
    • 我引用和引用的帮助文本也解释了它。试试format(as.Date("2019-12-31"), "%G-%V")
    猜你喜欢
    • 2020-12-26
    • 2020-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 2015-04-29
    • 2022-07-20
    • 2021-03-22
    相关资源
    最近更新 更多