Format multiple date formats in one columns using lubridate

后端 未结 2 516
星月不相逢
星月不相逢 2020-12-21 04:31

Sometimes I am given data sets that has two different date formats but common variables that have to been joined into one dataframe. Over the years, I\'ve tried various solu

2条回答
  •  -上瘾入骨i
    2020-12-21 05:36

    From the help on parse_date_time:

    ## ** how to use select_formats **
    ## By default %Y has precedence:
    parse_date_time(c("27-09-13", "27-09-2013"), "dmy")
    ## [1] "13-09-27 UTC"   "2013-09-27 UTC"
    
    ## to give priority to %y format, define your own select_format function:
    
    my_select <-   function(trained){
      n_fmts <- nchar(gsub("[^%]", "", names(trained))) + grepl("%y",     names(trained))*1.5
      names(trained[ which.max(n_fmts) ])
    }
    
    parse_date_time(c("27-09-13", "27-09-2013"), "dmy", select_formats = my_select)
    ## '[1] "2013-09-27 UTC" "2013-09-27 UTC"
    

提交回复
热议问题