Converting dates before January 1, 1970 in R

前端 未结 3 1558
予麋鹿
予麋鹿 2021-01-27 06:05

I am trying to convert a column of dates into Date objects in R, but I can\'t seem to get the desired results. These individuals have birth dates before January 1, 1970, so when

相关标签:
3条回答
  • 2021-01-27 06:27

    No need for add-on packages, base R is fine. But you need to specify the century:

    R> as.Date("1954-01-12")
    [1] "1954-01-12"
    R> 
    

    If you need non-default formats, just specify them:

    R> as.Date("19540112", "%Y%m%d")
    [1] "1954-01-12"
    R> 
    

    Edit: In case your data really comes in using the %y% format, and you happen to make the policy decision that the 19th century is needed , here is one base R way of doing it:

    R> d <- as.Date("540112", "%y%m%d")
    R> dlt <- as.POSIXlt(d)
    R> dlt$year <- dlt$year - 100
    R> as.Date(dlt)
    [1] "1954-01-12"
    R> 
    
    0 讨论(0)
  • 2021-01-27 06:28

    If everything is in the 1900s, its a one-liner - just format it with a two-digit year at the start and slap a 19 on the front and convert to a date. Again. Man this would look cool some %>% stuff:

    s = c("1/12/54","1/12/74")
    as.Date(format(as.Date(s,format="%d/%m/%y"), "19%y%m%d"), "%Y%m%d")
    # [1] "1954-12-01" "1974-12-01"
    

    If years from "69" to "99" are 1800s, then here's another one-liner:

    library(dplyr) # for pipe operator:
    s %>% as.Date(format="%d/%m/%y") %>% 
         format("%y%m%d") %>%
        (function(d){
           paste0(ifelse(d>700101,"18","19"),d)
           }) %>% 
      as.Date("%Y%m%d")
    
    ## [1] "1954-12-01" "1874-12-01"
    

    Note not thoroughly tested so might be some off-by-one errors or I've mixed months and days because you need to be ISO8601 Compliant

    0 讨论(0)
  • 2021-01-27 06:30

    I would do:

    library(lubridate)
    
    x <- as.Date("1/12/54", format = "%m/%d/%y")
    year(x) <- 1900 + year(x) %% 100
    
    > x
    [1] "1954-01-12"
    
    0 讨论(0)
提交回复
热议问题