在Date列上应用应用函数时遇到问题。日期显示不正确。需要有关此的帮助
> head(dataF)
[1] "4-Sep-06" "27-Oct-06" "8-Jan-07" "28-Jan-07" "5-Jan-07" "28-Jan-07"
> res <- apply(dataF, 2, dmy)
> head(res)
DateM
[1,] 1157328000
[2,] 1161907200
[3,] 1168214400
[4,] 1169942400
[5,] 1167955200
[6,] 1169942400
无论您想对输出做什么,当函数dmy
已经处理向量时,都不应该使用apply
或其表亲。只需使用
res <- dmy(dataF)
话虽如此,如果你只是想学习如何使用apply
,阿难的评论是正确的。以下内容也应为您提供正确的结果。
res <- lapply(dataF, dmy)
这里有一个更详细的例子,我们只替换了几列中的日期:
dataF <- data.frame(x = c("4-Sep-06", "27-Oct-06", "8-Jan-07",
"28-Jan-07", "5-Jan-07", "28-Jan-07"),
y = c("4-Jan-06", "27-Jan-06", "8-Feb-07",
"28-Feb-07", "5-Mar-07", "28-Mar-07"),
z = c(1:6))
dataF
# x y z
# 1 4-Sep-06 4-Jan-06 1
# 2 27-Oct-06 27-Jan-06 2
# 3 8-Jan-07 8-Feb-07 3
# 4 28-Jan-07 28-Feb-07 4
# 5 5-Jan-07 5-Mar-07 5
# 6 28-Jan-07 28-Mar-07 6
library(lubridate)
## The third column is not a date
## Just replace the first two columns directly
dataF[1:2] <- lapply(dataF[1:2], dmy)
dataF
# x y z
# 1 2006-09-04 2006-01-04 1
# 2 2006-10-27 2006-01-27 2
# 3 2007-01-08 2007-02-08 3
# 4 2007-01-28 2007-02-28 4
# 5 2007-01-05 2007-03-05 5
# 6 2007-01-28 2007-03-28 6
如果希望格式看起来像日期对象,请将其更改为日期对象。这样,它实际上是一个日期对象。
> dataF <- c("4-Sep-06", "27-Oct-06", "8-Jan-07",
"28-Jan-07", "5-Jan-07", "28-Jan-07")
> as.Date(dataF, "%d-%b-%y")
[1] "2006-09-04" "2006-10-27" "2007-01-08" "2007-01-28" "2007-01-05" "2007-01-28"