R change integer to three integers

前端 未结 3 1812
闹比i
闹比i 2021-01-23 01:35

I have this number

20101213 which is a representation of this data 2010 Dec 13th I want to extract the year, month and day numbers from that nu

3条回答
  •  借酒劲吻你
    2021-01-23 01:54

    You probably want to get this into a date-time format anyways for future computing, so how about:

    (x <- strptime(20101213, "%Y%m%d"))
    # [1] "2010-12-13 EST"
    

    This will enable you to do computations that you wouldn't have been able to with just the year, month number, and day number, such as grabbing the day of the week (0=Sunday, 1=Monday, ...) or day of the year:

    x$wday
    # [1] 1
    x$yday
    # [1] 346
    

    Further, you could easily extract the year, month number, and day of month number:

    c(x$year+1900, x$mon+1, x$mday)
    # [1] 2010   12   13
    

    Edit: As pointed out by @thelatemail, an alternative that doesn't involve remembering offsets is:

    as.numeric(c(format(x, "%Y"), format(x, "%m"), format(x, "%d")))
    # [1] 2010   12   13
    

提交回复
热议问题