0

I always thought the only difference between sapply and lapply is the first one produce a matrix while the second produce a list, but the difference is more than that I set a function like this:

nadate <- function(x) {
  ifelse(is.na(x),"True",as.Date(as.character(x),format="%Y%m%d"))}

numdate <- function(x) {
  if (all(is.na(x))) return (x)
  else if(!any(is.na(nadate(x)))) {
    as.Date(as.character(x),format="%Y%m%d")}
  else return (x)}

d is

ValueDate BookDate  TranAmt
1 20161219  20161219  123123.1
2 20161216  20161216  3234.2
3 20161216  20161216  42123.3

d3 <- lapply(d, numdate) # returns what I want

   ValueDate   BookDate    TranAmt
1  2016-12-19  2016-12-19  123123.1
2  2016-12-16  2016-12-16  3234.2
3  2016-12-16  2016-12-16  42123.3


d3 <- sapply(d, numdate) # suppose to return the same value but in a matrix, but it returns completely different values
ValueDate  BookDate
1 17154      17154
2 17151      17151
3 17151      17151
Cloud Li
  • 11
  • 4
  • `sapply` returns a vector, `lapply` returns a list, `apply` returns a vector/matrix/array depending on `MARGIN` and the function you supply – acylam Oct 13 '17 at 17:07
  • In fact, only `lapply` is consistent with it's output, always returning a list. The problem above is due to the fact that `apply` converts its input to a matrix prior to the computation. The matrix class overwrites the Date class, turning Date objects into integers. – lmo Oct 13 '17 at 17:10
  • 1
    `apply` works on a matrix/array. `lapply` and `sapply` work on one-dimensional-like things, such as vectors, lists (including data frames). `sapply` is a wrapper for `lapply` that *attempts* to simplify the result into a matrix or vector. `vapply` is `sapply` but with a specified return type. `mapply` is `sapply` but iterating in parallel over multiple arguments. – Gregor Thomas Oct 13 '17 at 17:10
  • imo's answer sounds right. But I did not understand very well, so why does the 5 digit number replace the date in sapply function? – Cloud Li Oct 13 '17 at 17:28
  • It has nothing to do with `sapply`, it's all because it's a matrix. Maybe see [Casting a Date matrix?](https://stackoverflow.com/q/9116490/903061) for explanation. Essentially, a `Date` class object has too much going on for it to fit inside the simple `matrix` class. Even `matrix(Sys.Date())` falls back to the numeric version of the date. – Gregor Thomas Oct 13 '17 at 17:35
  • Of course your example *shouldn't* work for a matrix because by definition the values of a matrix need to all be the same class. You can't have a matrix with numerics in some places and characters/factors/Dates etc. anywhere else. – Gregor Thomas Oct 13 '17 at 17:37

0 Answers0