Change the year in a datetime object in R?

前端 未结 3 699
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-18 08:53

I have the following:

\"0014-06-30\"

And I\'d like to change it to:

\"0000-06-30\"

How would I do this in

相关标签:
3条回答
  • 2020-12-18 09:11
    > x <- as.Date('0014-06-30')
    > x
    [1] "0014-06-30"
    > library(lubridate)
    > year(x)
    [1] 14
    > year(x) <- 0
    > x
    [1] "0000-06-30"
    
    0 讨论(0)
  • 2020-12-18 09:13

    I couldn't get the specific format by converting to as.Date. A regex option would be

    str1 <- "0014-06-30"
    as.Date(str1)
    #[1] "14-06-30"
    
    sub('\\d{2}(?=-)', '00', str1, perl=TRUE)
    #[1] "0000-06-30"
    
    0 讨论(0)
  • 2020-12-18 09:29

    I would offer the following function to fix a mixed vector of two and four digit dates (where you have have formatted a string as a date if starting with a string):

    library(lubridate)
    two_dig_year_cnvt <- function(z, year=2017){
        y <- as.numeric(format(z, '%Y'))
        range <- 2017 - 2000
        year(z) <- ifelse(y >= 0 & y <= range, 2000 + y, 
                          ifelse(y > range & y <= 200, 1900 + y, y))
        z
    }
    

    This says for two digit years 00-16, assume that 2000 was the intended century, and for years 17-200 assume the century was 1900. Else, return the original year. If you're dealing with 19th century dates then of course this method is a no-go.

    0 讨论(0)
提交回复
热议问题