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

后端 未结 3 1184
悲&欢浪女
悲&欢浪女 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条回答
  •  -上瘾入骨i
    2021-01-02 02:08

    Because there are so many ways in which a date can be passed in from files, databases etc and for the reason you mention of just being written in different orders or with different separators, representing the inputted date as a character string is a convenient and useful solution. R doesn't hold the actual dates as strings and you don't need to process them as strings to work with them.

    Internally R is using the operating system to do these things in a standard way. You don't need to manipulate strings at all - just perhaps convert some things from character to their numerical equivalent. For example, it is quite easy to wrap up both operations (forwards and backwards) in simple functions you can deploy.

    toDate <- function(year, month, day) {
        ISOdate(year, month, day)
    }
    
    toNumerics <- function(Date) {
        stopifnot(inherits(Date, c("Date", "POSIXt")))
        day <- as.numeric(strftime(Date, format = "%d"))
        month <- as.numeric(strftime(Date, format = "%m"))
        year <- as.numeric(strftime(Date, format = "%Y"))
        list(year = year, month = month, day = day)
    }
    

    I forego the a single call to strptime() and subsequent splitting on a separation character because you don't like that kind of manipulation.

    > toDate(2004, 12, 21)
    [1] "2004-12-21 12:00:00 GMT"
    > toNumerics(toDate(2004, 12, 21))
    $year
    [1] 2004
    
    $month
    [1] 12
    
    $day
    [1] 21
    

    Internally R's datetime code works well and is well tested and robust if a bit complex in places because of timezone issues etc. I find the idiom used in toNumerics() more intuitive than having a date time as a list and remembering which elements are 0-based. Building on the functionality provided would seem easier than trying to avoid string conversions etc.

提交回复
热议问题