将非标准日期格式字符串("April-20")转换为日期对象 R

Converting non-standard date format strings ("April-20") to date objects R

我有一个格式为 month_name-2_digit_year 的日期字符串向量,即

a = rbind("April-21", "March-21", "February-21", "January-21") 

我正在尝试将该向量转换为日期对象的向量。我知道这个问题与此非常相似:Convert non-standard date format to date in R 几年前发布的,但不幸的是,它没有回答我的问题。

我尝试了以下 as.Date() 调用来执行此操作,但它只是 returns NA 的向量。即

b = as.Date(a, format = "%B-%y")
b = as.Date(a, format = "%B%y")
b = as.Date(a, "%B-%y")
b = as.Date(a, "%B%y")

我也尝试使用 openxlsx 包中的 convertToDate 函数来做到这一点:

b = convertToDate(a, format = "%B-%y") 

我也尝试了以上所有方法,但使用单个字符串而不是向量,但产生了同样的问题。

我有点迷惑为什么这不起作用,因为这种格式在我的脚本中已经反向工作(也就是说,我有一个日期对象已经是 dd-mm-yyyy 格式并转换它到 month_name-yy 使用 %B-%y)。当字符串是非标准日期格式(如果您在美国,则为 dd-mm-yyy 或 mm-dd-yy 以外的任何格式)日期格式时,是否还有另一种从字符串到日期的方法?

郑重声明,我的 R 语言环境都是英国和英语。

提前致谢。

一个日期必须有日、月、年三者。转换为只需要月份和年份的 yearmon class,然后转换为下面 (1) 和 (2) 中的日期,或添加 (3) 中的日期。

(1) 和 (3) 给出月初,(2) 给出月底。

(3) 仅使用基础 R 中的函数。

还可以考虑根本不转换为 Date,而只使用 yearmon 对象,因为它们直接代表输入所代表的年份和月份。

library(zoo)

# test input
a <- c("April-21", "March-21", "February-21", "January-21") 

# 1
as.Date(as.yearmon(a, "%B-%y"))
## [1] "2021-04-01" "2021-03-01" "2021-02-01" "2021-01-01"

# 2
as.Date(as.yearmon(a, "%B-%y"), frac = 1)
## [1] "2021-04-30" "2021-03-31" "2021-02-28" "2021-01-31"

# 3
as.Date(paste(1, a), "%d %B-%y")
## [1] "2021-04-01" "2021-03-01" "2021-02-01" "2021-01-01"

除了动物园,还有哪个@G。 Grothendieck提到,你也可以使用时钟或lubridate。

时钟支持称为 year_month_day 的可变精度日历类型。在这种情况下,您需要 "month" 精度,然后您可以将日期设置为您想要的任何日期并转换回日期。

library(clock)

x <- c("April-21", "March-21", "February-21", "January-21") 

ymd <- year_month_day_parse(x, format = "%B-%y", precision = "month")
ymd
#> <year_month_day<month>[4]>
#> [1] "2021-04" "2021-03" "2021-02" "2021-01"

# First of month
as.Date(set_day(ymd, 1))
#> [1] "2021-04-01" "2021-03-01" "2021-02-01" "2021-01-01"

# End of month
as.Date(set_day(ymd, "last"))
#> [1] "2021-04-30" "2021-03-31" "2021-02-28" "2021-01-31"

最简单的解决方案可能是使用 lubridate::my(),它按“月然后年”的顺序解析字符串。这假设您想要一个月的第一天,这对您来说可能正确也可能不正确。

library(lubridate)

x <- c("April-21", "March-21", "February-21", "January-21") 

# Assumes first of month
my(x)
#> [1] "2021-04-01" "2021-03-01" "2021-02-01" "2021-01-01"