Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert character month name to date time object

Tags:

date

r

lubridate

I must be missing something simple.

I have a data.frame of various date formats and I'm using lubridate which works great with everything except month names by themselves. I can't get the month names to convert to date time objects.

> head(dates)
    From         To
1       June     August
2    January   December
3 05/01/2013 10/30/2013
4       July   November
5 06/17/2013 10/14/2013
6 05/04/2013 11/23/2013

Trying to change June into date time object:

> as_date(dates[1,1])
Error in charToDate(x) : 
  character string is not in a standard unambiguous format

> as_date("June")
Error in charToDate(x) : 
  character string is not in a standard unambiguous format
  • The actual year and day do not matter. I only need the month. zx8754 suggested using dummy day and year.
like image 940
Chris Avatar asked Sep 18 '25 16:09

Chris


2 Answers

lubridate can handle converting the name or abbreviation of a month to its number when it's paired with the rest of the information needed to make a proper date, i.e. a day and year. For example:

lubridate::mdy("August/01/2013", "08/01/2013", "Aug/01/2013")
#> [1] "2013-08-01" "2013-08-01" "2013-08-01"

You can utilize that to write a function that appends "/01/2013" to any month names (I threw in abbreviations as well to be safe). Then apply that to all your date columns (dplyr::mutate_all is just one way to do that).

name_to_date <- function(x) {
  lubridate::mdy(ifelse(x %in% c(month.name, month.abb), paste0(x, "/01/2013"), x))
}

dplyr::mutate_all(dates, name_to_date)
#>         From         To
#> 1 2013-06-01 2013-08-01
#> 2 2013-01-01 2013-12-01
#> 3 2013-05-01 2013-10-30
#> 4 2013-07-01 2013-11-01
#> 5 2013-06-17 2013-10-14
#> 6 2013-05-04 2013-11-23
like image 187
camille Avatar answered Sep 21 '25 06:09

camille


The following is a crude example of how you could achieve that.

Given that dummy values are fine:

match(dates[1, 1], month.abb)

The above would return you, given that we had Dec in dates[1. 1]:

12

To generate the returned value above along with dummy number in a date format, I tried:

tmp = paste(match(dates[1, 1], month.abb), "2013", sep="/")

which gives us:

12/2013

and then lastly:

result = paste("01", tmp, sep="/")

which returns:

01/12/2013

I am sure there are more flexible approaches than this; but this is just an idea, which I just tried.

like image 30
Unheilig Avatar answered Sep 21 '25 07:09

Unheilig