问题
I have a problem with dates convertion. If I use ymd in apply, it returns a numeric, or if I use only ymd it's works. Someone would have any idea ?
library(lubridate)
a <- data.frame(dates1=c("2011-01-01",'2011-02-01','2011-03-01'),
dates2=c("2013-01-01",'2013-02-01','2013-03-01'))
apply(a, 2, FUN = function(x) ymd(x))
dates1 dates2
[1,] 1293840000 1356998400
[2,] 1296518400 1359676800
[3,] 1298937600 1362096000
ymd(a$dates1)
[1] "2011-01-01 UTC" "2011-02-01 UTC" "2011-03-01 UTC"
ymd(a$dates2)
[1] "2013-01-01 UTC" "2013-02-01 UTC" "2013-03-01 UTC"
回答1:
Use lapply()
:
lapply(a, function(x) ymd(x))
Update/Explaination
The apply()
documentation states:
In all cases the result is coerced by as.vector to one of the basic vector types before the dimensions are set, so that (for example) factor results will be coerced to a character array.
As J.Ulrich states in the comments to this answer "dates aren't strictly vectors". lapply()
is very similar to apply()
, however it will return a list rather than a vector. Hence its ability to handle dates.
回答2:
apply
tries to simplify it, using as.matrix
if input X is two-dimensional, see this example:
as.matrix(ymd("2013-01-01"))
[,1]
[1,] 15706
?apply
Details
If X is not an array but an object of a class with a non-null dim value (such as a data frame), apply attempts to coerce it to an array via as.matrix if it is two-dimensional (e.g., a data frame) or via as.array.
回答3:
Here is an option using mutate_each
library(dplyr)
a %>%
mutate_each(funs(ymd))
# dates1 dates2
#1 2011-01-01 2013-01-01
#2 2011-02-01 2013-02-01
#3 2011-03-01 2013-03-01
来源:https://stackoverflow.com/questions/38180051/apply-and-lubridate