2013-05-08 34 views
10

我在格式數據四捨五入次最接近的小時中的R

time <- c("16:53", "10:57", "11:58") 

我想創建其中每個這些時間的被舍入爲最接近的小時的新列。我似乎無法讓POSIX命令爲我工作。

as.character(格式(DATA2 $時間, 「%H:%M」))

錯誤format.default(結構(as.character(X),名稱=名稱( X),昏暗朦朧=(X):? 無效 '微調' 的說法

別說使用圓形命令任何人都可以提出建議

+1

'format'用於在另一個方向走(從日期時間到特定表示)我不是確定是否有部分日期時間的課程,例如只包含小時和分鐘。 – Frank 2013-05-08 15:23:48

+1

http://stackoverflow.com/questions/16041093/round-a-posix-date-and-time-posixct-to-a-date-relative-to-a-timezone – 2013-05-08 15:27:17

+0

類似於:'as.POSIXlt(strptime (tt,format =「%H:%M」)+ 30 * 60)$ hour' – Arun 2013-05-08 15:29:23

回答

13
## Example times 
x <- c("16:53", "10:57", "11:58") 

## POSIX*t objects need both date and time specified 
## Here, the particular date doesn't matter -- just that there is one. 
tt <- strptime(paste("2001-01-01", x), format="%Y-%m-%d %H:%M") 

## Use round.Date to round, then format to format 
format(round(tt, units="hours"), format="%H:%M") 
# [1] "17:00" "11:00" "12:00" 
+0

你真的不需要添加日期,如果你使用'strptime(x,「%H:%M」),那麼當前日期將被自動添加。' – eddi 2013-05-08 16:33:32

+2

@eddi - 酷,但任何可能讓你進入的機會在夏令時轉換的特定時間遇到麻煩? (我*說*這一天並不重要,但出於這個原因選擇了一個我認爲任何地方都沒有DLT轉換的地方...) – 2013-05-08 16:36:19

+0

看不到它爲什麼 - 我只是檢查它可以正常工作,據我所知。 – eddi 2013-05-08 16:44:17