嗨,我的数据中有多种日期格式。如何转换为日期格式as.posixct
以下是示例数据。
df <- data.frame(date=c('01-12-2019','44166','12-08-2019','01/27/2020'))
任何帮助将不胜感激。
一种可能是分别处理不同的日期格式(使用中的tryFormats
参数可能会发生这种情况,as.Date
但是日期格式缺乏统一性,因此使用起来不太可能。):
df$date <-stringr::str_replace_all(df$date,"/","-") #format won't work without this
good_formats <-df[grepl("\\D",df$date),]
bad_formats<- df[!grepl("\\D",df$date),] #They're not bad, just think they're less programmer friendly
good_formats<-as.Date(good_formats,
format=c("%d-%m-%Y","%d-%m-%Y","%m-%d-%Y"))
bad_formats <- as.Date(as.numeric(bad_formats),origin="1970-01-01")
data.frame(date=c(good_formats,bad_formats))
结果:
date
1 2019-12-01
2 2019-08-12
3 2020-01-27
4 2090-12-03
结果的结构:
'data.frame': 4 obs. of 1 variable:
$ date: Date, format: "2019-12-01" ...
数据:
data.frame(date=c('01-12-2019','44166','12-08-2019','01/27/2020')
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句