如何在 R 中以小于 1 秒的单位填充日期向量?

How can I pad a vector of dates by units of less than 1 second in R?

我想弄清楚如何使用小于 1 秒的单位将时间间隔添加到 R 中的日期向量。如您所见,填充一秒间隔有效,但小数位失败。我环顾四周,似乎 R 中没有 "milliseconds" 单元。有什么方法可以填充时间向量,间隔小于 1 秒?

> require(padr)
> require(dplyr)
> options(digits.secs=3)
> start = as.POSIXct("2020-01-28 03:31:22.209 EST", format = "%Y-%m-%d %H:%M:%OS")
> end = as.POSIXct("2020-01-28 05:31:22.209 EST", format = "%Y-%m-%d %H:%M:%OS")
> 
> minz <- seq(start, end, units = "minutes", by = "1 min")
> head(minz)
[1] "2020-01-28 03:31:22.209 EST" "2020-01-28 03:32:22.209 EST" "2020-01-28 03:33:22.209 EST" "2020-01-28 03:34:22.209 EST"
[5] "2020-01-28 03:35:22.209 EST" "2020-01-28 03:36:22.209 EST"
> secz <- as.data.frame(minz) %>% pad('1 sec')
> head(secz)
                     minz
1 2020-01-28 03:31:22.209
2 2020-01-28 03:31:23.209
3 2020-01-28 03:31:24.209
4 2020-01-28 03:31:25.209
5 2020-01-28 03:31:26.209
6 2020-01-28 03:31:27.209
> half_secz <- as.data.frame(minz) %>% pad('0.5 sec')
Error in seq.int(0, to0 - from, by) : invalid '(to - from)/by'
> head(secz)
                     minz
1 2020-01-28 03:31:22.209
2 2020-01-28 03:31:23.209
3 2020-01-28 03:31:24.209
4 2020-01-28 03:31:25.209
5 2020-01-28 03:31:26.209
6 2020-01-28 03:31:27.209

我们可以使用 seq,因为它将 by 参数指定为 0.5。

start = as.POSIXct("2020-01-28 03:31:22.209", format = "%Y-%m-%d %H:%M:%OS",tz = "UTC")
end =  as.POSIXct("2020-01-28 05:31:22.209", format = "%Y-%m-%d %H:%M:%OS",tz = "UTC")

seq(start, end, by = 0.5) %>% head

#[1] "2020-01-28 03:31:22.209 UTC" "2020-01-28 03:31:22.709 UTC"
#[3] "2020-01-28 03:31:23.209 UTC" "2020-01-28 03:31:23.709 UTC"
#[5] "2020-01-28 03:31:24.209 UTC" "2020-01-28 03:31:24.709 UTC"

或者如果你想在 secz 数据帧中使用它

tidyr::complete(secz, minz = seq(min(minz), max(minz), by = 0.5))

#    minz                   
#   <dttm>                 
# 1 2020-01-28 03:31:22.209
# 2 2020-01-28 03:31:22.709
# 3 2020-01-28 03:31:23.209
# 4 2020-01-28 03:31:23.709
# 5 2020-01-28 03:31:24.209
# 6 2020-01-28 03:31:24.709
# 7 2020-01-28 03:31:25.209
# 8 2020-01-28 03:31:25.709
# 9 2020-01-28 03:31:26.209
#10 2020-01-28 03:31:26.709
# … with 14,391 more rows