rounding times to the nearest hour in R [duplicate]

别等时光非礼了梦想. 提交于 2019-12-18 15:30:51

问题


I have data in the format

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

etc

I would like to create a new column where each of these times is rounded to the nearest hour. I cannot seem to get the POSIX command to work for me.

as.character(format(data2$time, "%H:%M"))

Error in format.default(structure(as.character(x), names = names(x), dim = dim(x), : invalid 'trim' argument

Let alone use the round command. Can anyone advise?


回答1:


## 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"


来源:https://stackoverflow.com/questions/16444242/rounding-times-to-the-nearest-hour-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!