I am trying to use sapply to get the max date in a column but it is returning a number instead of a date. Any idea how to resolve this? I can\'t seem to figure out why this is
We need to use lapply
instead of sapply
lapply(mtcars, max)
as sapply
returns a vector
because of the simplify=TRUE
default argument and vector
can hold only a single class. As there are numeric columns, the 'Date' column (which is stored as integer) gets coerced to integer
value. However, we can still use sapply
if we use simplify = FALSE
to return a list
.
sapply(mtcars, max, simplify = FALSE)
Regarding the use of apply
apply(mtcars,2,max)
I would not recommend using apply
as this will convert to matrix and matrix can hold only a single class. Here, it will be all character
output as the 'Date' class got converted to character
.
Regarding the problem mentioned by OP in the comments, when we have output that belong to different class, we could either use list
or data.frame
(as data.frame
is a list
) as c
i.e. concatenate returns a vector
and as mentioned above, it can hold only a single class.
do.call(rbind, lapply(mtcars, function(x)
data.frame(Class=class(x), Max=max(x, na.rm=TRUE))))