转换为日期和剥离时间?

convert to date and strip time?

我有一些数据如下所示:

dates <- structure(c(1L, 2L, 4L, 3L), .Label = c("Sat, 18 Nov 2017 00:00:00 GMT", 
                                             "Thu, 16 Nov 2017 00:00:00 GMT", "Tue, 14 Nov 2017 00:00:00 GMT", 
                                             "Wed, 15 Nov 2017 00:00:00 GMT"), class = "factor")

我想将其转换为日期格式而不是将其作为一个因素。另外,我想删除 00:00:00 GMT 因为它没有意义

我试过 lubridate 但格式有问题:

library(lubridate)
mdy(dates)
Warning message:
All formats failed to parse. No formats found.

这看起来有效:

as.POSIXct(dates, format = '%a, %d %b %Y %H:%M:%S')
#[1] "2017-11-18 GMT" "2017-11-16 GMT" "2017-11-15 GMT" "2017-11-14 GMT"

我们也可以使用 lubridate 包中的 dmy_hms

library(lubridate)

dmy_hms(dates, tz = "GMT")
# [1] "2017-11-18 GMT" "2017-11-16 GMT" "2017-11-15 GMT" "2017-11-14 GMT"

像这样使用as.Date。它最后忽略了垃圾,所以这是有效的。没有使用包。

as.Date(dates, "%a, %d %b %Y")
## [1] "2017-11-18" "2017-11-16" "2017-11-15" "2017-11-14"