首页 文章

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

提问于
浏览
2

我一定很遗憾 .

我有一个各种日期格式的data.frame,我正在使用lubridate,除了 month names by themselves 之外的所有东西都很好用 . 我无法将月份名称转换为日期时间对象 .

> 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更改为date time对象:

> 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
  • 实际年和日无所谓 . 我只需要一个月 . zx8754建议使用虚拟日和年 .

2 回答

  • 2

    使用自定义功能:

    # 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
    
  • 3

    以下是如何实现这一目标的粗略示例 .

    假设虚拟值很好:

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

    鉴于 dates[1. 1] 中有 Dec ,上述内容将返回给您:

    12
    

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

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

    这给了我们:

    12/2013
    

    最后:

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

    返回:

    01/12/2013
    

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

相关问题