我可以使用基础 tryCatch 在向量上应用函数吗? [英] Can I apply a function over a vector using base tryCatch?

查看:34
本文介绍了我可以使用基础 tryCatch 在向量上应用函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从具有混合日期格式的向量中解析日期(使用 lubridate 函数).

I'm trying to parse dates (using lubridate functions) from a vector which has mixed date formats.

departureDate <- c("Aug 17, 2020 12:00:00 AM", "Nov 19, 2019 12:00:00 AM", "Dec 21, 2020 12:00:00 AM",
"Dec 24, 2020 12:00:00 AM", "Dec 24, 2020 12:00:00 AM", "Apr 19, 2020 12:00:00 AM", "28/06/2019",
"16/08/2019", "04/02/2019", "10/04/2019", "28/07/2019", "26/07/2019", 
"Jun 22, 2020 12:00:00 AM", "Apr 5, 2020 12:00:00 AM",  "May 1, 2021 12:00:00 AM")

因为我一开始没有注意到,我尝试使用 lubridate::mdy_hms(departureDate) 进行解析,这导致格式与此不同的日期的 NA 值的解析器.由于格式可能会随向量的随机位置发生变化,我尝试使用以下句子:

As I didn't notice at first, I tried to parse with lubridate::mdy_hms(departureDate) which resulted in NA values for dates whose format differs from that of the parser. As the format may change on random positions of the vector I tried to use the following sentence:

departureDate <- tryCatch(mdy_hms(departureDate), 
                             warning = function(w){return(dmy(departureDate))})

这带来了更多的NA,因为它只应用了警告函数调用.有没有办法用我的方法解决这个问题?

Which brought even more NA's as it only applied the warning function call. Is there a way to solve this by using my approach?

提前致谢

推荐答案

我们可以使用 lubridate::parse_date_time ,它可以采用多种格式.

We can use lubridate::parse_date_time which can take multiple formats.

lubridate::parse_date_time(departureDate, c('%b %d, %Y %I:%M:%S %p', '%d/%m/%Y'))

#[1] "2020-08-17 UTC" "2019-11-19 UTC" "2020-12-21 UTC" "2020-12-24 UTC"
#[5] "2020-12-24 UTC" "2020-04-19 UTC" "2019-06-28 UTC" "2019-08-16 UTC"
#[9] "2019-02-04 UTC" "2019-04-10 UTC" "2019-07-28 UTC" "2019-07-26 UTC"
#[13] "2020-06-22 UTC" "2020-04-05 UTC" "2021-05-01 UTC"

由于 departureDate 中的月份名称是英文,因此您需要语言环境也为英文.

Since in departureDate month name is in English, you need the locale to be English as well.

参考 如何更改 R 的语言环境?有非英语语言环境.

Refer How to change the locale of R? if you have non-English locale.

这篇关于我可以使用基础 tryCatch 在向量上应用函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆