Converting dates before January 1, 1970 in R

前端 未结 3 1601
予麋鹿
予麋鹿 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: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

提交回复
热议问题