How to convert in both directions between year,month,day and dates in R?

后端 未结 3 1204
悲&欢浪女
悲&欢浪女 2021-01-02 01:34

How to convert between year,month,day and dates in R?

I know one can do this via strings, but I would prefer to avoid converting to strings, partly because maybe the

3条回答
  •  灰色年华
    2021-01-02 02:27

    Found one solution for going from date to year,month,day.

    Let's say we have a date object, that we'll create here using ISOdate:

    somedate <- ISOdate(2004,12,21)
    

    Then, we can get the numerical components of this as follows:

    unclass(as.POSIXlt(somedate))
    

    Gives:

    $sec
    [1] 0
    
    $min
    [1] 0
    
    $hour
    [1] 12
    
    $mday
    [1] 21
    
    $mon
    [1] 11
    
    $year
    [1] 104
    

    Then one can get what one wants for example:

    unclass(as.POSIXlt(somedate))$mon
    

    Note that $year is [actual year] - 1900, month is 0-based, mday is 1-based (as per the POSIX standard)

提交回复
热议问题