2012-12-07 12 views
8

Co mam do tej pory, to kolumna danych z datami w różnych formatach znaków. Niektóre pojawiają się we wzorcu %d.%m.%Y, niektóre w %m/%d/%Y:Jak zmienić wiele formatów daty w tej samej kolumnie?

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" 

chcę je jako Date() w jednym formacie, ale R odmawia oczywiście.
Spróbowałem więc najpierw je zmienić za pomocą separatora: „”

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

analogicznie do Daktyle. Ale to nie zadziałało.

Jak mogę je wszystkie zmienić na jeden format, aby móc z nimi pracować?

Odpowiedz

16
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 oto poprzedzający sposób dostosowany do sytuacji, w której masz trzy (lub więcej) różnych formatów:

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" 
+0

Dzięki ! Działa w porządku. – Rob

12

Lubię lubridate ze względu na łatwość użycia:

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 
+0

Doceniam/myślę, że wartość jawnie definiująca preferencje jest tutaj ogromna. –

Powiązane problemy