【问题标题】:Converting date to a day of week in R [duplicate]在R中将日期转换为星期几[重复]
【发布时间】:2012-08-12 17:19:43
【问题描述】:

可能重复:
Find the day of a week in R

我有 11-01-2011 等天的数据。但我想添加相应的数据 日期为星期一,星期二等。是否有任何包含日期信息的 R 包?

【问题讨论】:

    标签: r


    【解决方案1】:

    这里有一些信息来创建你自己的库或例程

    常量:

    day_of_month

        the day of the month
        e.g. if input mm-dd-yyy then dd
    

    march = 1
    april = 2
    may = 3
    ...
    

    年份

    yy[yy]  (last to digits from yyyy)
       *subtract 1 if month jan or feb
        e.g. if input date is 02-01-2012 (mm-dd-yyyy)
             year =  (12-1) = 11
    

    世纪

    [yy]yy  (first two digits from yyyy)
         e.g. if input year is 2012 then 20 = century
         * year 2000, 1900, ... are 20-1, 19-1 respectively
    

    算法

    step1: floor(century / 4)
    
    step2: year
    
    step3: floor(year/4)
    
    step4: floor(month*2.6 -0.2)  #this is the leap year correction
    
    step5: day_of_month
    
    step6: add step1...step5
    
    step7: divide by 7  # modulo 7 in codespeak
    
    step8: the remainder is the day of the week
    

    解释结果:

    Sun = 0, Mon = 1, Tues = 3, etc..
    

    不是图书馆,而是公共服务的叮当声……

    “阅读:你知道的更多”

    参考:http://bit.ly/PqF0M0

    【讨论】:

      【解决方案2】:
      weekdays(as.Date('16-08-2012','%d-%m-%Y'))
      [1] "Thursday"
      

      【讨论】:

      • 我总是忘记weekdays() 在base R中。+1
      【解决方案3】:

      lubridate 包非常适合这类东西。

      > wday(as.Date('16-08-2012','%d-%m-%Y'))
      [1] 5
      > wday(as.Date('16-08-2012','%d-%m-%Y'), label=TRUE)
      [1] Thurs
      Levels: Sun < Mon < Tues < Wed < Thurs < Fri < Sat
      > wday(as.Date('16-08-2012','%d-%m-%Y'), label=TRUE, abbr = FALSE)
      [1] Thursday
      Levels: Sunday < Monday < Tuesday < Wednesday < Thursday < Friday < Saturday
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-01-29
        • 2014-01-11
        • 1970-01-01
        • 2020-12-14
        • 1970-01-01
        • 2015-08-02
        • 2016-01-05
        • 2020-01-23
        相关资源
        最近更新 更多