如何将字符和日期转换为日期? [英] How to convert character and dates to dates?

查看:86
本文介绍了如何将字符和日期转换为日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据来自excel.日期采用dd/mm/yyyy格式:

My data comes from excel. The dates are in dd/mm/yyyy format:

certificado$fecha <- c("22/02/2019", "43679", "22/02/2019", "22/01/2019", "28/10/2019", 
"18/09/2019")

但是,R正在读取某些日期,例如mm/dd/yyyy.我的代码应该将它们全部转换为特定格式.

However, R is reading some dates as mm/dd/yyyy. My code is supposed to convert all of them to an specific format.

certificados$Fecha <- as.Date(certificados$Fecha,format = "%d/%m/%Y")

但是由于日期格式问题,我无法获得NAs.

But im getting NAs due to date format issues.

推荐答案

如果无法从源头上解决此问题,则此代码将找到两种格式:

If you cannot fix this at the source, this code finds both formats:

vec <- c("22/02/2019", "43679", "22/02/2019", "22/01/2019", "28/10/2019", "18/09/2019")
out <- as.Date(vec, format = "%d/%m/%Y")
out
# [1] "2019-02-22" NA           "2019-02-22" "2019-01-22" "2019-10-28" "2019-09-18"

isna <- is.na(out)
out[isna] <- as.Date(as.integer(vec[isna]), origin = "1900-01-01")
out
# [1] "2019-02-22" "2019-08-04" "2019-02-22" "2019-01-22" "2019-10-28" "2019-09-18"

这篇关于如何将字符和日期转换为日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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