Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
335 views
in Technique[技术] by (71.8m points)

r - How to change multiple Date formats in same column?

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"

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

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

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I like lubridate for its ease of use:

library(lubridate) 

# note added ugly formats below
data <- data.frame(initialDiagnose = c("14.01.2009", "9/22/2005", 
        "4/21/2010", "28.01.2010", "09.01.2009", "3/28/2005", 
        "04.01.2005", "04.01.2005", "Created on 9/17/2010", "03 01 2010"))

mdy <- mdy(data$initialDiagnose) 
dmy <- dmy(data$initialDiagnose) 
mdy[is.na(mdy)] <- dmy[is.na(mdy)] # some dates are ambiguous, here we give 
data$initialDiagnose <- mdy        # mdy precedence over dmy
data
#   initialDiagnose
#       2009-01-14
#       2005-09-22
#       2010-04-21
#       2010-01-28
#       2009-09-01
#       2005-03-28
#       2005-04-01
#       2005-04-01
#       2010-09-17
#       2010-03-01

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...