R change integer to three integers

前端 未结 3 1804
闹比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:50

    If you don't want to deal with string representation you could also just use mod function like this:

    # using mod
    year  = floor(value/10000)
    month = floor((value %% 10000)/100)
    day = value %% 100
    

    Which will then extract the relevant parts of the number as expected.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2021-01-23 02:12
    year <- as.numeric(substr(as.character(value),start = 1,stop = 4))
    month <- as.numeric(substr(as.character(value),start = 5,stop = 6))
    day <- as.numeric(substr(as.character(value),start = 7,stop = 8))
    
    0 讨论(0)
提交回复
热议问题