This question already has an answer here:
Round a POSIX date and time (posixct) to a date relative to a timezone

(1个答案)


7年前关闭。





我有格式的数据

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


等等

我想创建一个新列,其中每个时间都四舍五入到最近的小时。我似乎无法使POSIX命令为我工作。


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


格式错误。default(structure(as.character(x),names = names(x),dim = dim(x),:
无效的“修剪”参数

更不用说使用round命令了。有人可以建议吗?

最佳答案

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

关于r - 将时间四舍五入到R中最接近的小时数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16444242/

10-12 20:00