我希望将时间从一个因子转换为一个日期。
对于示例数据框:
date.time <- structure(list(date = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L), .Label = "02/02/2013", class = "factor"), time = structure(1:9, .Label = c("07:55:40",
"07:55:50", "07:56:00", "07:56:10", "07:56:20", "07:56:30", "07:56:40",
"07:56:50", "07:57:00"), class = "factor")), .Names = c("date",
"time"), class = "data.frame", row.names = c(NA, -9L))
我希望学习如何将日期和时间列转换为真实的日期/时间(即不是因素)。
有人可以解释为什么这不起作用吗?
date.time$time <- as.POSIXlt(date.time$time, format="%H:%M:%S")
根据我的理解,POSIXlt需要一个时间和日期 - 是吗?当我运行此代码时,它会添加今天的日期。
是否可以:(a)将两列分别转换为日期和时间列,以及(b)将它们整合在一起形成时间和日期列?
答案 0 :(得分:2)
很抱歉错过了你想要合并这两列。尝试
date.time$date.time <- paste(as.character(date.time$date), as.character(date.time$time))
date.time$date.time <- as.POSIXlt(date.time$date.time, format="%d/%m/%Y %H:%M:%S")
date.time
class(date.time$date.time)
> date.time
date time date.time
1 02/02/2013 07:55:40 2013-02-02 07:55:40
2 02/02/2013 07:55:50 2013-02-02 07:55:50
3 02/02/2013 07:56:00 2013-02-02 07:56:00
4 02/02/2013 07:56:10 2013-02-02 07:56:10
5 02/02/2013 07:56:20 2013-02-02 07:56:20
6 02/02/2013 07:56:30 2013-02-02 07:56:30
7 02/02/2013 07:56:40 2013-02-02 07:56:40
8 02/02/2013 07:56:50 2013-02-02 07:56:50
9 02/02/2013 07:57:00 2013-02-02 07:57:00
> class(date.time$date.time)
[1] "POSIXlt" "POSIXt"