本文介绍了转换序列日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在阅读Excel时遇到问题.带有日期的列正在按顺序读取某些单元格,而另一些则作为日期读取,如下所示.
I am having problems with reading excel. A column with dates is being read some cells in serial and others as date as below.
date<-c("43942", "43945", "43952", "17/05/2020", "17/05/2020", "18/05/2020", "19/05/2020", "18/05/2020", "22/05/2020")如何将下面的向量转换为日期?我将其作为字符串放置,因为这是我要转换的列在阅读后的外观.
How could I convert the vector below to dates? I put it as a string because this is how the column I want to convert looks after reading.
命令
as.Date(date, origin = "1899-12-30")返回错误和
as.Date(as.numeric(date), origin = "1899-12-30")在NA中转换非序列日期.
convert in NA the non-serial dates.
推荐答案您可以按任意顺序分两个步骤进行处理.
You can handle this in two steps in any order.
将数字转换为日期
new_date <- as.Date(as.numeric(date), origin = "1899-12-30")这将为无法转换为数字的日期返回警告.
This will return warnings for dates that cannot be converted to numeric.
使用"dmy" 格式
new_date[is.na(new_date)] <- as.Date(date[is.na(new_date)], "%d/%m/%Y") #Or using lubridate's dmy #new_date[is.na(new_date)] <- lubridate::dmy(date[is.na(new_date)]) new_date #[1] "2020-04-21" "2020-04-24" "2020-05-01" "2020-05-17" "2020-05-17" "2020-05-18" #[7] "2020-05-19" "2020-05-18" "2020-05-22"更多推荐
转换序列日期
发布评论