Apply and lubridate

烈酒焚心 提交于 2020-01-25 06:07:13

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!