问题
I have data that formats dates like so:
Tue Oct 25 2016
Tue Oct 25 2016
Tue Oct 25 2016
Wed Oct 26 2016
Wed Oct 26 2016
Wed Oct 26 2016
I would like this to be in a format in which R
can use it as a date (i.e. 2016-10-25
). Any help?
回答1:
Edit: I somehow missed that you had the day of the week as well.
This can also be done in base using as.Date
with the correct formatting string. In this case %a
would give you the abbreviated day of the week,%B
will give you the month abbreviation, %d
will give you the minimum digit day (i.e. 2 instead of 02), and %Y
will give you the four digit year. In the example these are all separated by a single space, so the format string should reflect that.
datesx <- c("Tue Oct 25 2016", "Tue Oct 25 2016", "Wed Oct 26 2016", "Wed Oct 26 2016", "Wed Oct 26 2016", "Wed Oct 26 2016")
as.Date(datesx,format = "%a %B %d %Y")
[1] "2016-10-25" "2016-10-25" "2016-10-26" "2016-10-26" "2016-10-26" "2016-10-26"
回答2:
The anytime package has anydate()
which is pretty good and tries a number of different formats. Here we still need to chop off the (redundant) weekday:
R> library(anytime)
R> anydate(c("Oct 25 2016", "Oct 25 2016", "Oct 25 2016",
+ "Oct 26 2016", "Oct 26 2016", "Oct 26 2016"))
[1] "2016-10-25" "2016-10-25" "2016-10-25"
[4] "2016-10-26" "2016-10-26" "2016-10-26"
R>
回答3:
This answer does not use extra packages:
dates <- c("Tue Oct 25 2016",
"Tue Oct 25 2016",
"Tue Oct 25 2016",
"Wed Oct 26 2016",
"Wed Oct 26 2016",
"Wed Oct 26 2016")
# Remove day of the week
dates <- sub("\\w{3} ", "", dates)
# Convert to Date
dates <- as.Date(dates, "%b %d %Y", origin = "1970-01-01")
dates
#[1] "2016-10-25" "2016-10-25" "2016-10-25" "2016-10-26" "2016-10-26"
# "2016-10-26"
来源:https://stackoverflow.com/questions/46653891/convert-text-date-in-r