Efficiently convert a date column in data.table

后端 未结 4 1020
遇见更好的自我
遇见更好的自我 2020-12-16 21:13

I have a large data set with many columns containing dates in two different formats:

\"1996-01-04\" \"1996-01-05\" \"1996-01-08\" \"1996-01-09\" \"1996-01-10         


        
4条回答
  •  执笔经年
    2020-12-16 21:55

    Since you know beforehand there are only two date formats, this is easy. The format argument to as.Date is vectorized:

    as_date_either <- function(x) {
        format_vec <- rep_len("%Y-%m-%d", length(x))
        format_vec[grep("/", x, fixed = TRUE)] <- "%m/%d/%Y"
        as.Date(x, format = format_vec)
    }
    

    Edited: replaced ifelse with subset assignment, which is faster

提交回复
热议问题