如何更改同一列中的多个日期格式

编程入门 行业动态 更新时间:2024-10-27 12:39:49
本文介绍了如何更改同一列中的多个日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

到目前为止,我已经是一个包含不同字符格式的数据帧列。一些出现在%d。%m。%Y 模式中,一些在%m /%d /%Y $

What I've got so far is a dataframe column with dates in different character formats. A few appear in the %d.%m.%Y pattern, some in %m/%d/%Y :

data$initialDiagnose = as.character(data$initialDiagnose) data$initialDiagnose[1:10] [1] "14.01.2009" "9/22/2005" "4/21/2010" "28.01.2010" "09.01.2009" "3/28/2005" "04.01.2005" "04.01.2005" "9/17/2010" "03.01.2010"

我想他们作为Date()以一种格式,但R拒绝当然。 所以我试着首先通过分隔符更改它们:

I want them as Date() in one format, but R refuses of course. So I tried at first to change them by the separator:

data$initialDiagnose[grep('/', data$initialDiagnose)] = as.character.Date(data$initialDiagnose[grep('/', data$initialDiagnose)], format = '%m/%d/%Y')

类似于'。'日期。但是它没有起作用。

Analogue to the '.' dates. But it didn't work.

如何将它们全部更改为一种格式,我可以与他们一起工作?

How can I change them all to one format, that I can work with them?

推荐答案

a <- as.Date(data$initialDiagnose,format="%m/%d/%Y") # Produces NA when format is not "%m/%d/%Y" b <- as.Date(data$initialDiagnose,format="%d.%m.%Y") # Produces NA when format is not "%d.%m.%Y" a[is.na(a)] <- b[!is.na(b)] # Combine both while keeping their ranks data$initialDiagnose <- a # Put it back in your dataframe data$initialDiagnose [1] "2009-01-14" "2005-09-22" "2010-04-21" "2010-01-28" "2009-01-09" "2005-03-28" "2005-01-04" "2005-01-04" "2010-09-17" "2010-01-03"

Additionnaly这里是适用于您有三种(或多种)不同格式的情况的上述方法:

Additionnaly here's the preceding method adapted to a situation where you have three (or more) different formats:

data$initialDiagnose [1] 14.01.2009 9/22/2005 12 Mar 97 4/21/2010 28.01.2010 09.01.2009 3/28/2005 Levels: 09.01.2009 12 Mar 97 14.01.2009 28.01.2010 3/28/2005 4/21/2010 9/22/2005 multidate <- function(data, formats){ a<-list() for(i in 1:length(formats)){ a[[i]]<- as.Date(data,format=formats[i]) a[[1]][!is.na(a[[i]])]<-a[[i]][!is.na(a[[i]])] } a[[1]] } data$initialDiagnose <- multidate(data$initialDiagnose, c("%m/%d/%Y","%d.%m.%Y","%d %b %y")) data$initialDiagnose [1] "2009-01-14" "2005-09-22" "1997-03-12" "2010-04-21" "2010-01-28" "2009-01-09" "2005-03-28"

更多推荐

如何更改同一列中的多个日期格式

本文发布于:2023-10-26 11:07:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1529955.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多个   如何更改   日期   格式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!