How to convert character and dates to dates?

五迷三道 提交于 2020-01-25 06:52:12

问题


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")

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")

But im getting NAs due to date format issues.


回答1:


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"


来源:https://stackoverflow.com/questions/58880848/how-to-convert-character-and-dates-to-dates

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!