【问题标题】:How to convert a column with different date formats to a common date format?如何将具有不同日期格式的列转换为通用日期格式?
【发布时间】:2015-08-12 12:37:14
【问题描述】:
Date  
01/01/2013 #mm/dd/yyyy  
12122015 #mmddyyyy  
2014-03-21 #yyyy-mm-dd  
95.10.12 #yy.mm.dd  

我有一个不同格式的“日期”列。如何清理它并将它们转换为单一日期格式?
附加信息:类(日期)是因素。

【问题讨论】:

  • 我们可以使用library(lubridate)?guess_formats
  • 您可以使用foo(parse_date_time(Date, guess_formats(Date, c('dmy', 'ymd')))),其中foo 来自链接。和Date <- c('01/01/2013', '12122015', '2014-03-21', '95.10.12')
  • 在“03-03-2013”​​之类的情况下,清理数据时如何区分月份和日期(因为两者相同)?
  • 您可能需要将这些特殊情况分开。
  • 我的数据集中几乎 50-60% 的值与我提到的一样。那么如何才能高效清洁呢??

标签: r date datetime date-format data-cleaning


【解决方案1】:

最简单的方法是使用lubridate 包。

Date=c( 
   "01/01/2013" #mm/dd/yyyy  
  ,"12122015" #mmddyyyy  
  ,"2014-03-21" #yyyy-mm-dd  
  ,"95.10.12" #yy.mm.dd  
)

library(lubridate)

# list of functions in lubridate that 
# translate text to POSIXct: you only need to know the
# order of the data (e.g. mdy = month-day-year).
funs <- c("mdy","dym","ymd","dmy","myd","ydm")

# vector to store results
dates <- as.POSIXct(rep(NA,length(Date)))

# we try everything lubridate has. There will be some warnings
# e.g. because mdy cannot translate everything. You can ignore this.
for ( f in funs ){
  dates[is.na(dates)] <- do.call(f,list(Date[is.na(dates)]))  
}
dates

> dates
[1] "2013-01-01 01:00:00 CET" "2015-12-12 01:00:00 CET" "2013-01-01 01:00:00 CET" "2015-12-12 01:00:00 CET"

【讨论】:

    猜你喜欢
    • 2013-06-21
    • 1970-01-01
    • 2017-05-01
    • 2020-08-04
    • 1970-01-01
    • 2014-02-25
    • 1970-01-01
    • 1970-01-01
    • 2018-02-12
    相关资源
    最近更新 更多