a.powell
a.powell

Reputation: 1722

Convert Text Date in R

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?

Upvotes: 0

Views: 448

Answers (3)

RealViaCauchy
RealViaCauchy

Reputation: 337

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"

Upvotes: 6

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"

Upvotes: 0

Dirk is no longer here
Dirk is no longer here

Reputation: 368201

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> 

Upvotes: 2

Related Questions