Chris Chris - 2 months ago 12
R Question

Convert character month name to date time object

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.


Answer

Using a custom function:

# dummy data
df1 <- read.table(text = "
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", header = TRUE, as.is = TRUE)

# custom function
myFun <- function(x, dummyDay = "01", dummyYear = "2013"){
  require(lubridate)

  x <- ifelse(substr(x, 1, 3) %in% month.abb,
              paste(match(substr(x, 1, 3), month.abb),
                    dummyDay,
                    dummyYear, sep = "/"), x)
  #return date
  mdy(x)
}

res <- data.frame(lapply(df1, myFun))

res
#         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