涂抹和润滑

Apply and lubridate

日期转换有问题。如果我在应用程序中使用 ymd,它 returns 一个数字,或者如果我只使用 ymd 它是有效的。 有人会知道吗?

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"

使用lapply():

lapply(a, function(x) ymd(x))

Update/Explaination

apply() 文档指出:

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.

正如 J.Ulrich 在对 this answer "dates aren't strictly vectors" 的评论中所述。 lapply()apply() 非常相似,但它 return 是一个列表而不是向量。因此它能够处理日期。

apply 尝试简化它,如果输入 X 是二维的,则使用 as.matrix,请参见此示例:

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.

这是一个使用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