舍入时间到R的最近时刻

use*_*387 11 datetime timestamp r posixct

我有格式的数据

time <-  c("16:53", "10:57", "11:58")
Run Code Online (Sandbox Code Playgroud)

等等

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

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

format.default中的错误(结构(as.character(x),names = names(x),dim = dim(x),:invalid'trim'参数

更别说使用round命令了.任何人都可以建议吗?

Jos*_*ien 15

## 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"
Run Code Online (Sandbox Code Playgroud)

  • @eddi - 很酷,但是有任何机会可以让您在夏令时变换的特定时间遇到麻烦吗?(我*说*那天没关系,但是出于这个原因选择了一个我认为没有任何地方有DLT转换......) (2认同)
  • @eddi如果您在美国,请尝试将您的计算机系统日期设置为2013年3月10日(今年夏令时开始),然后运行`round(strptime("1:31","%H:%M) "),"小时")`.R返回`[1]"2013-03-10 03:00:00 PDT"` - 正是我想要避免的. (2认同)