我一定错过了一些简单的东西。
我有一个各种日期格式的 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
Run Code Online (Sandbox Code Playgroud)
尝试将 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
Run Code Online (Sandbox Code Playgroud)
lubridate当与确定正确日期(即日和年)所需的其余信息配对时,可以将月份的名称或缩写转换为其数字。例如:
lubridate::mdy("August/01/2013", "08/01/2013", "Aug/01/2013")
#> [1] "2013-08-01" "2013-08-01" "2013-08-01"
Run Code Online (Sandbox Code Playgroud)
您可以利用它来编写一个函数,将“/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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18448 次 |
| 最近记录: |