2

After looking at Why does mapply not return date-objects?, I still cannot fix my problem.

The problem:

I have a matrix of date values and I want to convert them to date objects by the following function:

convert_endDate <- function(e){
    d <- paste(e[1], e[2],e[3], sep = "-")
    print(as.Date(strptime(d, format = "%Y-%m-%d")))
    return(as.Date(strptime(d, format = "%Y-%m-%d"))) 
}

apply(end, 1,convert_endDate)

However, it always returns numbers to me: [1] 16276 15850 14085 13569 13293 12473 12046 11316 10950 10950

Now, how can I convert this to Dates ???

The data matrix end is below:

      eyr em   
 [1,] 2014  7 25
 [2,] 2013  5 25
 [3,] 2008  7 25
 [4,] 2007  2 25
 [5,] 2006  5 25
 [6,] 2004  2 25
 [7,] 2002 12 25
 [8,] 2000 12 25
 [9,] 1999 12 25
[10,] 1999 12 25
Community
  • 1
  • 1
mynameisJEFF
  • 4,073
  • 9
  • 50
  • 96

2 Answers2

2

Both paste and as.Date are vectorized, so no need for apply. Because as.Date first tries the format "%Y-%m-%d", i.e. the same format which results from paste here, there is no need for an explicit format argument.

m <- matrix(data = c(2014, 7, 25, 2013,  5, 25), ncol = 3, byrow = TRUE)
m
#      [,1] [,2] [,3]
# [1,] 2014    7   25
# [2,] 2013    5   25

date <- as.Date(paste(m[ , 1], m[ , 2], m[ , 3], sep = "-"))
date
# [1] "2014-07-25" "2013-05-25"

str(date)
# Date[1:2], format: "2014-07-25" "2013-05-25"

Also see ?apply: "In all cases the result is coerced by as.vector to one of the basic vector types".

Henrik
  • 65,555
  • 14
  • 143
  • 159
1
end <- matrix(c(2014, 7, 25, 2013, 5, 25, 2008, 7, 25, 2007, 2, 25, 2006, 5, 25), ncol=3, byrow=T)
res <- apply(end,1, convert_endDate)

 as.Date(res, origin="1970-01-01")
 #[1] "2014-07-25" "2013-05-25" "2008-07-25" "2007-02-25" "2006-05-25"
akrun
  • 874,273
  • 37
  • 540
  • 662