我的日期格式如下: - Wed Apr 25 2018 00:00:00 GMT-0700 (Pacific Standard Time)
或43167
或Fri May 18 2018 00:00:00 GMT-0700 (PDT)
混合在1列中。以简单YYYY-mm-dd (2018-04-13)
格式转换所有这些内容的最简单方法是什么?这是专栏:
dates <- c('Fri May 18 2018 00:00:00 GMT-0700 (PDT)',
'43203',
'Wed Apr 25 2018 00:00:00 GMT-0700 (Pacific Standard Time)',
'43167','43201',
'Fri May 18 2018 00:00:00 GMT-0700 (PDT)',
'Tue May 29 2018 00:00:00 GMT-0700 (Pacific Standard Time)',
'Tue May 01 2018 00:00:00 GMT-0700 (PDT)',
'Fri May 25 2018 00:00:00 GMT-0700 (Pacific Standard Time)',
'Fri Apr 06 2018 00:00:00 GMT-0700 (PDT)','43173')
预期格式:2018-05-18, 2018-04-13, 2018-04-25, ...
答案 0 :(得分:1)
我相信之前曾多次询问过类似的问题。但是,那里 是一个需要特别关注的关键点:
以整数形式给出的日期的origin
是什么(或者可以转换为精确的整数字符串)?
如果从Windows版本的Excel导入数据,则必须使用origin = "1899-12-30"
。有关详细信息,请参阅help(as.Date)
和the Other Applications section of the R Help Desk article by Gabor Grothendieck and Thomas Petzoldt中的示例部分。
为了转换日期时间字符串,使用mdy_hms()
包中的lubridate
函数。另外,我使用data.table
语法来简洁:
library(data.table)
data.table(dates)[!dates %like% "^\\d+$", new_date := as.Date(lubridate::mdy_hms(dates))][
is.na(new_date), new_date := as.Date(as.integer(dates), origin = "1899-12-30")][]
dates new_date 1: Fri May 18 2018 00:00:00 GMT-0700 (PDT) 2018-05-18 2: 43203 2018-04-13 3: Wed Apr 25 2018 00:00:00 GMT-0700 (Pacific Standard Time) 2018-04-25 4: 43167 2018-03-08 5: 43201 2018-04-11 6: Fri May 18 2018 00:00:00 GMT-0700 (PDT) 2018-05-18 7: Tue May 29 2018 00:00:00 GMT-0700 (Pacific Standard Time) 2018-05-29 8: Tue May 01 2018 00:00:00 GMT-0700 (PDT) 2018-05-01 9: Fri May 25 2018 00:00:00 GMT-0700 (Pacific Standard Time) 2018-05-25 10: Fri Apr 06 2018 00:00:00 GMT-0700 (PDT) 2018-04-06 11: 43173 2018-03-14
显然,选择属于Windows版本Excel的原点的假设似乎成立。
如果只需要Date
值的向量:
data.table(dates)[!dates %like% "^\\d+$", new_date := as.Date(lubridate::mdy_hms(dates))][
is.na(new_date), new_date := as.Date(as.integer(dates), origin = "1899-12-30")][, new_date]
[1] "2018-05-18" "2018-04-13" "2018-04-25" "2018-03-08" "2018-04-11" "2018-05-18" [7] "2018-05-29" "2018-05-01" "2018-05-25" "2018-04-06" "2018-03-14"