gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 03:55:45 24 4
gpt4 key购买 nike

我一定错过了一些简单的事情。

我有一个各种日期格式的 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
  • 实际年份和日期并不重要。我只需要一个月。 zx8754建议使用虚拟的日期和年份。

最佳答案

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

关于r - 将字符月份名称转换为日期时间对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39762543/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com