2015-04-22 31 views
3

我希望將時間從因子轉換爲日期。從因子轉換時間/日期

對於樣本數據幀:

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需要一個時間和日期 - 是嗎?當我運行這個代碼時,它增加了今天的日期。

是否有可能:(1)單獨轉換兩列日期和時間欄和(b)將它們集成在一起,形成一個時間和日期列?

回答

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" 
+0

感謝 - 這真的很好的瞭解。我也想只是有時間(不是日期)格式正確。沒有相應的日期,這是不可能的? –

+0

不是我所知。在這樣的數據結構中,如何處理跨越午夜的時間計算? –

+0

夠公平的。如果我想在我的date.time列中添加10分鐘 - 這可能嗎?我用之前... >>庫(代下)>> date.time $時間< - 倍(as.character(date.time $時間))>> date.time $結束時間< - 活動$ TIME +倍( 「00:00:10」)......但這不是工作了。我如何在POSIXlt日期上添加時間? –

2

你也可以嘗試包lubridate

library(lubridate) 
dmy(date.time$date) 
[1] "2013-02-02 UTC" "2013-02-02 UTC" "2013-02-02 UTC" "2013-02-02 UTC" "2013-02-02 UTC" "2013-02-02 UTC" "2013-02-02 UTC" "2013-02-02 UTC" "2013-02-02 UTC" 
hms(date$time) 
[1] "7H 55M 40S" "7H 55M 50S" "7H 56M 0S" "7H 56M 10S" "7H 56M 20S" "7H 56M 30S" "7H 56M 40S" "7H 56M 50S" "7H 57M 0S"