0

I have a dataframe with a date column, and I want to convert it. With this example,

DF <- data.frame(name = paste("A", 1:5, sep = ""), 
                 birth = c("16131", "2014-07-04", "16257", "15982", "2014-07-04"))

as.Date(DF$birth, origin = "1970-01-01")

It's returning me a message error :

Error in charToDate(x) : 
  la chaîne de caractères n'est pas dans un format standard non ambigu

In english, the string is in a ambiguous standard format. Thanks in advance!

bartektartanus
  • 15,284
  • 6
  • 74
  • 102
Mostafa90
  • 1,674
  • 1
  • 21
  • 39

3 Answers3

2

The problem is that some of your values require integer to Date conversion and some others character to Date. To complicate it even more, your DF$birth is a factor. You can split it, apply as.Date to the integer parts and the character parts, and then join them:

f <- function(x) {
    # Thanks to @RichardScriven for the improvement
    v1 <- as.numeric(v2 <- as.character(x))
    v1 <- as.Date(v1, origin = "1970-01-01")
    v2[!is.na(v1)] <- NA
    v2 <- as.Date(v2, origin = "1970-01-01")
    as.Date(ifelse(is.na(v1), v2, v1), origin = "1970-01-01")
}

f(DF$birth)
# [1] "2014-03-02" "2014-07-04" "2014-07-06" "2013-10-04" "2014-07-04"
konvas
  • 14,126
  • 2
  • 40
  • 46
1
as.Date(DF$birth[1], origin = "1970-01-01")
## Błąd w charToDate(x) : 
##   łańcuch tekstowy nie jest w standardowym jednoznacznym formacie
as.Date(DF$birth[2], origin = "1970-01-01")
## [1] "2014-07-04"

every element of birth column have to match this "1970-01-01" data pattern. Otherwise you will get the error.

bartektartanus
  • 15,284
  • 6
  • 74
  • 102
1

You may also use:

 library(gsubfn)

 DF$birth <- as.Date(gsubfn("^[[:digit:]]+$",
 ~ format(as.Date(as.numeric(x),origin="1970-01-01"),"%Y-%m-%d"),
   as.character(DF$birth) ))
 DF$birth 
 #[1] "2014-03-02" "2014-07-04" "2014-07-06" "2013-10-04" "2014-07-04"
akrun
  • 874,273
  • 37
  • 540
  • 662