将字符月份名称转换为日期时间对象

Convert character month name to date time object

我一定是漏掉了一些简单的东西。

我有一个 data.frame 的各种日期格式,我正在使用 lubridate,它适用于除 月份名称之外的所有内容 。我无法将月份名称转换为日期时间对象。

> 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

正在尝试将 June 更改为日期时间对象:

> 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

使用自定义函数:

# 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

以下是如何实现该目标的粗略示例。

鉴于虚拟值很好:

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

上面会 return 你,假设我们在 dates[1. 1] 中有 Dec:

12

为了生成上面的 returned 值以及日期格式的虚拟数字,我尝试了:

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

这给了我们:

12/2013

然后最后:

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

其中 return 个:

01/12/2013

我相信还有比这更灵活的方法;但这只是一个想法,我刚刚尝试过。

lubridate 可以处理将月份的名称或缩写转换为它的数字,当它与制作正确日期所需的其余信息配对时,即日期和年份。例如:

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

您可以利用它来编写一个将“/01/2013”​​附加到任何月份名称的函数(为了安全起见,我也加入了缩写)。然后将其应用于所有日期列(dplyr::mutate_all 只是一种方法)。

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